我有按键功能,可以根据按键打开网页。例如,按下“Alt + s”按键将打开about网页,问题是它似乎无法在Google Chrome浏览器中运行。
我需要它才能在所有方面工作,但似乎无法让它正常工作。
<html>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
// hides all DIVs with the CLASS container
// and displays the one with the ID 'home' only
$(".container").css("display", "none");
$("#home").css("display", "block");
// makes the navigation work after all containers have bee hidden
showViaLink($("ul#navigation li a"));
// listens for any navigation keypress activity
$(document).keypress(function(e) {
e.preventDefault();
if (e.altKey) {
switch (e.which) {
// user presses the "a"
case 97:
showViaKeypress("#home");
break;
// user presses the "s" key
case 115:
showViaKeypress("#about");
break;
// user presses the "d" key
case 100:
showViaKeypress("#contact");
break;
// user presses the "f" key
case 102:
showViaKeypress("#awards");
break;
// user presses the "g" key
case 103:
showViaKeypress("#links");
}
}
});
});
// shows a given element and hides all others
function showViaKeypress(element_id) {
$(".container").css("display", "none");
// if multiple keys are pressed rapidly this will hide all but the last pressed key's div
$(".container").hide(1);
$(element_id).slideDown("slow");
}
// shows proper DIV depending on link 'href'
function showViaLink(array) {
array.each(function(i) {
$(this).click(function() {
var target = $(this).attr("href");
$(".container").css("display", "none");
$(target).slideDown("slow");
});
});
}
});//]]>
</script>
</head>
<body>
<div id="header">
<h1>jQuery Keypress Navigation</h1>
<ul id="navigation">
<li><a href="#home">Home ( a )</a></li>
<li><a href="#about">About ( s )</a></li>
<li><a href="#contact">Contact ( d )</a></li>
<li><a href="#awards">Awards ( f )</a></li>
<li><a href="#links">Links ( g )</a></li>
</ul>
</div>
<div style="display: block;" id="home" class="container">
<h2>Welcome!</h2>
<p>Thanks for taking the time to visit my site</p>
</div>
<div style="display: none;" id="about" class="container">
<h2>About Me</h2>
<p>Web design is more than just another job, is more than hobby.</p>
</div>
<div style="display: none;" id="contact" class="container">
<h2>No Spam Please</h2>
<p>Gifts? Job offers? Compliments? They are all welcome.</p>
</div>
<div style="display: none;" id="awards" class="container">
<h2>Awards, So Many ...</h2>
<p>If I was to count all of them, we would be here for quite a while. I wish.</p>
</div>
<div style="display: none;" id="links" class="container">
<h2>Cool Sites</h2>
<p>Make sure you pay a visit to these sites:</p>
</div>
<div id="footer">
<p>&nbps;</p>
</div>
</body>
</html>
答案 0 :(得分:0)
问题在于keydown
和keypress
之间的区别。使用alt
时,keypress
键会更改键码值。
alt
+ a
= 229 a
= 97 alt
+ a
= 65 a
= 65 来自文档:
请注意,keypress docs,keydown和keyup提供一个代码,指示按下哪个键,而keypress指示输入了哪个字符。例如,小写的“a”将通过keydown和keyup报告为65,但按keypress报告为97。所有事件都将大写的“A”报告为65。由于这种区别,当捕捉箭头键等特殊键击时,
.keydown()
或.keyup()
是更好的选择。
您可以通过更改为keydown
听众(ala @ adeneo的建议)或正确编辑您的密码来解决此问题。