可以使用事件偵聽器來偵聽按鍵的鍵碼哪。你可以在<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