我设计了一个具有不同div的单页网站。如何为其分配键盘功能?因此,如果我按“回车”,页面应该采取“下一步”按钮的行动,并显示下面创建的div。类似地,当我按“退格键”时,页面应该执行“上一步”按钮的操作,并显示上面创建的div。请帮帮忙。
发布于 2016-01-14 13:37:17
您可以使用jQuery来实现这一点。
$(document).keypress(function (e){
if(e.keyCode == 13) // Enter key
{
// your action here, for example
$('#buttonNext').click();
}
else if(e.keyCode == 8) // BackSpace
{
// your action here, for example
$('#buttonPrev').click();
}
});发布于 2016-01-14 13:54:32
这里有一个你正在寻找的例子。请注意:我还没有实现退格键的用法;使用退格键是危险的,因为它可能会将用户送到最后一页,从而产生意想不到的结果。相反,请使用左右箭头键或enter键进行切换。
$(function() {
$("#two").hide();
$("body").keyup(function(event) {
if (event.keyCode === 39 || event.keyCode === 13) { //Right Key or Enter
$("#one").hide();
$("#two").show();
} else if (event.keyCode === 37) { //Left Key
$("#one").show();
$("#two").hide();
}
});
});.blue,
.red {
color: white;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="blue" id="one">
This is the first example
</div>
<div class="red" id="two">
And this is the second
</div>
</body>
Example.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function() {
$("#two").hide();
$("body").keyup(function(event) {
if (event.keyCode === 39 || event.keyCode === 13) {
$("#one").hide();
$("#two").show();
} else if (event.keyCode === 37) {
$("#one").show();
$("#two").hide();
}
});
});
</script>
<style>
.blue, .red {
color: white;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
</style>
</head>
<body>
<div class="blue" id="one">
This is the first example
</div>
<div class="red" id="two">
And this is the second
</div>
</body>
</html>https://stackoverflow.com/questions/34782297
复制相似问题