繁体   English   中英

如何在javascript中启用箭头键

[英]how to enable arrow keys in javascript

在我的应用程序中,我为文本字段(用户名)编写了Java脚本验证。 因此,它仅允许字母,空格,退格键和箭头在文本字段中移动上一个和下一个字母。 我的代码在mozila firefox中运行正常,但在chrome和IE中却不允许使用箭头键。

我的代码是这样的。

<input class="form-control input-lg" onkeypress="return isCharacterKey(event)" onkeyup="capitalize(this)" id="firstNameSpaceCapital"/>

//This function allows space,backspace,alphabets and arrow keys
function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    return false;
}

//This method is used to capitalize the first letter in the text field
function capitalize(obj) {
    obj.value = obj.value.charAt(0).toUpperCase() + obj.value.slice(1);
}

//This method is used to capitalize the first letter after space
$('#firstNameSpaceCapital').on('keyup', function () {
    $(this).val(function (i, val) {
        return val.replace(/(\s)(\S)/g, function ($0, $1, $2) {
            return $1 + $2.toUpperCase();
        });
    });
});

我会这样解决您的问题:

请注意,只有css才需要大写(至少在您出现的情况下)

小提琴

HTML

<input class="form-control input-lg" id="firstNameSpaceCapital" />

CSS

.input-lg {text-transform:capitalize;}

JS

$('#firstNameSpaceCapital').on('keypress', isCharacterKey);

function isCharacterKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 32 || charCode == 8 || (charCode >= 37 && charCode <= 40) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
        return true;
    }
    evt.preventDefault();
}

祝好运!

return isCharacterKey(event)

event未定义,请改用this

return isCharacterKey(this)

我认为捕获键盘事件不是一个好主意。 因为用户可以使用鼠标粘贴一些文本。 所以,我建议使用oninput事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM