keydown
イベントリスナーを使用して、キープレスをリッスンできます。<input>
畑などに使えます。keydown イベントは DOM をバブルdocument
アップするため、オブジェクトでそれを使用して、ページ上の任意のキー押下をキャッチできます。
$(function () {
$(document).keydown(function (evt) {
alert("Key pressed: " + evt.keyCode);
});
});
各キープレスにはコードがあります。上記のコードを Web ページで使用すると、下向き矢印のキー コードが 40 であることがわかります。ハンドラーでif
orswitch
ステートメントを使用して、これをソロにすることができます。
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
}
});
});
更新:上にスクロールするには、2 つのことを行います。keydown
ハンドラーを次のように変更します。
$(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();
}
}
に基づいて、ページにない最後の新しい見出しを見つけるscrollToLast()
関数を作成します。scrollToNew()
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);
}
}