당신은 키 누름을 수신하기 위해 keydown
이벤트 리스너를 사용할 수 눌러 진 키 코드를 결정해야합니다. <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
}
});
});
업데이트 여기에 기능을 함께 사용하여 원본 코드의 변종입니다 : 위쪽으로 스크롤하려면 두 가지 작업을 수행하십시오. 페이지에없는 마지막 새 제목을 발견 scrollToNew()
의 해제를 기반으로 scrollToLast()
기능을
$(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();
}
}
및 쓰기 :에 keydown
핸들러를 변경
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
위의 편집 ... – davegurnell
대단히 감사합니다! 완벽하게 작동합니다. – Ted