我正在尝试以下代码。它应该在按下 shift
键时将输入的 sh
属性更改为 1,并在释放时恢复为 0
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$(document).on("keyup","body",function(e) {
if (e.which == 16) {
$("input").attr("sh","0");
}
});
$(document).on("keydown","body",function(e) {
if (e.which == 16) {
$("input").attr("sh","1");
}
});
});
</script>
</head>
<body>
<input type = 'text' sh = '0'/>
<p>Just checking</p>
</body>
</html>
它工作正常,除非执行这一系列事件。在输入未聚焦时按 shift 键。 (Firebug 显示 sh
正如预期的那样变成 1)。现在仍然按下该键,将注意力集中在输入上。现在右键单击输入。弹出上下文菜单。现在,如果您释放 shift
键(让上下文菜单保留),Firebug 会显示 sh
仍然是 1。您在上下文菜单外单击以使其运行,甚至单击paste
选项将剪贴板文本粘贴到输入中,sh
仍然为 1。如果您再次按下并释放 shift
,只有 sh
再次变为 0。
知道如何解决这个问题吗?
最佳答案
以下对您有帮助吗? 我不确定我是否正确模拟了您的场景,但似乎对我有用。我在 Chrome 中测试过。
$(文档).ready(函数(){
$(document).keyup(function (e) {
if (e.which == 16) {
$("input").attr("sh", "0");
console.log($("input").attr("sh"));
}
});
$(document).keydown(function (e) {
if (e.which == 16) {
$("input").attr("sh", "1");
console.log($("input").attr("sh"));
}
});
//Works... (holding shift will raise keydown as much as I hold the key...)
//$(document).keyup(function (e) {
// if (e.keyCode == 16) {
// console.log("Shift was released...");
// }
//});
//$(document).keydown(function (e) {
// if (e.keyCode == 16) {
// console.log("Shift was pressed down...");
// }
//});
});
关于javascript - 上下文菜单事件后未注册 Keyup 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15321086/