可以使用事件侦听器来侦听按键的键码哪。你可以在<input>
等字段上使用。由于KEYDOWN事件bubble了DOM,你可以用它在document
对象捕捉任何按键在页面上:
$(function() {
$(document).keydown(function (evt) {
alert("Key pressed: " + evt.keyCode);
});
});
每个按键都有一个代码。如果你在你的网页使用上面的代码,你会看到向下箭头键码是40.你可以独唱这一点用在处理程序的if
或switch
声明:
jQuery(function() {
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
alert("You pressed down.");
}
});
});
现在你需要绑定到实际跳转到下一个标题的代码中。我建议将代码抽象为一个函数,以便您可以将它用于按键和点击。下面是函数,用你的原代码变体使用它一起:
// Here is the function:
function scrollToNew() {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
// Here is your original code, modified to use the function:
jQuery(function() {
$("#next").click(scrollToNew);
});
最后,你可以在按键代码从那里添加和调用函数:
function scrollToNew() {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
jQuery(function() {
$("#next").click(scrollToNew);
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
}
});
});
更新:向上滚动,做两件事。更改处理程序:
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
} else if (evt.keyCode == 38) { // up arrow
evt.preventDefault();
scrollToLast();
}
}
和编写基于断scrollToNew()
一个scrollToLast()
功能找到的最后一个新的标题,是不是在页面上:
function scrollToLast() {
scrollTop = $(window).scrollTop();
var scrollToThis = null;
// Find the last element with class 'new' that isn't on-screen:
$('.new').each(function(i, h2) {
h2top = $(h2).offset().top;
if (scrollTop > h2top) {
// This one's not on-screen - make a note and keep going:
scrollToThis = h2;
} else {
// This one's on-screen - the last one is the one we want:
return false;
}
});
// If we found an element in the loop above, scroll to it:
if(scrollToThis != null) {
$.scrollTo(scrollToThis, 800);
}
}
非常感谢,这个作品!为了能够使用箭头键,我需要添加什么? – Ted 2010-01-30 18:41:47
编辑在上面... – davegurnell 2010-01-31 09:10:00
非常感谢!完美的作品。 – Ted 2010-01-31 13:52:05