I wrote a code snippet for "shift key" keydown and keyup events for the mozilla but it is not working as I expect. Code:
<html>
<head>
<title>Testing Page</title>
<script type="text/javascript">
var key_capslock = 0;
var key_shift = 0;
function print1(){ window.alert("shift status" + key_shift);}
function print2(){ window.alert("shift status开发者_开发百科" + key_shift);}
function keyset(evt){
evt.preventDefault();
if(evt.keyCode == 16){
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
}
print1();
return;
}
function keyrelease(evt){
evt.preventDefault();
if(evt.keyCode == 16){
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
}
print2();
return;
}
function init(){
document.body.setAttribute("contentEditable", true);
document.body.addEventListener("keydown", keyset, false);
document.body.addEventListener("keyup", keyrelease, false);
}
</script>
</head>
<body onload="init()">
<br>
<body>
</html>
Steps: 1. Press the shift key (keydown and keyup events occur). 2. alert comes with shift status (print1 function runs). I click that. Expected: alert should come with shift status (print2 function should run). Actual: print2 function does not run.
If I press shift key second time then print2 function runs. I don't understand how the mozilla handling addEventListener function. Can someone please help me to resolve this issue? I don't want to use any third party framework to resolve this issue (jquery, dojo etc).
Thanks
Your code is actually fine, but the alert message takes the focus from the browser, preventing it from detecting keyup
.
If you change the functions to write to a div, for instance, you will see that both functions work:
http://jsfiddle.net/jtbowden/VqNvG/
Although, I don't understand this code:
if(key_shift == 0 ){key_shift = 1; evt.stopPropagation();}
else {key_shift = 0; evt.stopPropagation();}
If you are in keyset
, key_shift should always be 1 it seems, rather than toggling:
function keyset(evt){
evt.preventDefault();
if(evt.keyCode == 16){
key_shift = 1;
evt.stopPropagation();
}
print1();
return;
}
function keyrelease(evt){
evt.preventDefault();
if(evt.keyCode == 16){
key_shift = 0;
evt.stopPropagation();
}
print2();
return;
}
精彩评论