2013-03-10 61 views
2

我正在尝试以下代码。它应该与输入的sh属性更改为1,每当shift键被按下,并恢复到0发布键盘事件未在contextmenu事件后注册

<!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键(让contextmenu保持不变),Firebug会显示sh仍然为1.您可以单击contextmenu以外的其他设备,或者单击paste选项将剪贴板文本粘贴到输入中,仍然可以使用sh 1.如果再次按下并释放shift,则只有sh再次变为0。

任何想法如何解决这个问题?

+0

您是否需要检查所有'文档'上的'shift'键或输入是否足够? – 2013-03-10 10:42:47

+0

而不是“身体”尝试“*”。希望这会有所帮助。 – 2013-03-10 10:46:45

+0

@KundanSinghChouhan,没有好运的伴侣,如果我使用'*',它仍然是1! – SexyBeast 2013-03-10 11:12:45

回答

0

以下内容对您有帮助吗? 我不确定我是否正确模拟了您的场景,但似乎适用于我。我在Chrome中进行了测试。

$(文件)。就绪(函数(){

$(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..."); 
// } 
//}); 

});