Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - event.altKey not working in chrome and IE

Assume we have this code:

<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<script type="text/javascript">
var p = 0;

function reset()
{
    // some efforts
}

function code(e) {
    e = e || window.event;
    return(e.keyCode || e.which);
}
window.onload = function(){
    document.onkeypress = function(e){
    var key = code(e);      
    if(key == 38 || key == 40)
    {}
    else if(e.altKey)
    {
        alert('altkey pressed');
    }
    else
    {
        // Another THING!
    }
    };
};
</script>

</head>
<body style="padding:30px; font-size:30px;font-family: Courier;">
<span onclick="reset();" accesskey="r"></span>
</body>
</html>

It works great in Firefox but not in IE an Chrome.
When I change alt into shift it works on all browsers. but as you may notice, I wanted to use this for Shortcut key and I think this is a problem of Alt key in Chrome and IE (because both use Alt for accesskey attribute but Firefox uses Alt+Shift as mentoned here).
So guys what you suggest me to do ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can not detect alt button on chrome because it enables the window menu, so your page lose focus and the event "keypress" is not called. The event "keydown" on the other hand is called so you can use it with no problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...