Blazor 按鍵事件和 KeyCodes

傑森

我正在 Razor 控件庫中創建一個控件。我試圖只允許在文本框中按下幾個鍵。他們是:

  1. 任何大於 0 的數字。這包括小數
  2. 字母“N”或“n”
  3. 允許用戶複製/粘貼(control+c 和 control+v)。
  4. 允許箭頭和tab鍵

通過使用 Keycode,我可以在 Javascript 中輕鬆完成此操作。在 JS 中,我會這樣做:

keyPress: function (e) {
        var datatype = e.currentTarget.getAttribute("data-type");
        settings.valueChange.call();
        //add 110, 190 for decimal          
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
            // Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A
            ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
            // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
            // let it happen, don't do anything
            if (e.keyCode == 86) {
                //PASTE                
            }
            return;
        }
        if (e.keyCode === 78) {
            e.preventDefault();               
            //its an N, do some stuff
        } else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    }

但是,我將如何在 Blazor/Razor 中做到這一點?KeyboardEventArgs 似乎沒有提供 KeyCode。我可以使用 jsInterop 來調用我的 JS 函數,但同樣,KeyboardEventArgs 不提供 JS KeyCode。如何在 Blazor 中完成此操作或獲取數字 KeyCode,以便將其傳遞給我的 JS 函數?

阿拉馬卡南布拉

您可以使用更多 Blazor 方式來做到這一點,並在每次更改文本時檢查字符串。

@using System.Text.RegularExpressions;
<input @bind-value="@InputValue" @bind-value:event="oninput"/>
<h4>@InputValue </h4>

@code {
    private string _inputVal = "";
    public string InputValue {
        get => _inputVal;
        set { 
        if((double.TryParse(value,out double d) && d>0)//is the number like 1.23
          || value.ToLower()=="n" || value=="" )//or is N,n or empty str
            _inputVal = value;
        }
        }
}

粘貼和箭頭鍵按預期工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章