2010-01-30 11 views
3

링크를 클릭하면 "new"클래스로 다음 div로 스크롤하는 scrollTo jQuery 플러그인을 성공적으로 구현했습니다. 그러나 화살표 키를 사용하여 같은 클래스의 다음/이전 div로 위아래로 스크롤 할 수 있기를 바랍니다.jQuery에서 화살표 키 사용 scrollTo

나는 인터넷을 들여다 보았지만 이것을하는 방법을 찾을 수 없었다. 나는 JS에 매우 익숙해 져서 아주 간단한 지시 사항에 감사 할 것입니다! 여기

는 관련 코드 :

<script type="text/javascript"> 
jQuery(function($){ 

$('<div id="next_arrow"></div>') 
    .prependTo("body") //append the Next arrow div to the bottom of the document 
    .click(function(){ 
    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 
    } 
    }); 
    }); 

}); 
</script> 

내가 화살표 키가 작동하려면이에 추가해야합니까?

덕분에, 테드

답변

7

당신은 키 누름을 수신하기 위해 keydown 이벤트 리스너를 사용할 수 눌러 진 키 코드를 결정해야합니다. &lt;input&gt; 필드 등에서이 값을 사용할 수 있습니다. 를 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); 
    } 
} 
+0

대단히 고맙습니다. 화살표 키를 사용하려면 무엇을 추가해야합니까? – Ted

+0

위의 편집 ... – davegurnell

+0

대단히 감사합니다! 완벽하게 작동합니다. – Ted

0

당신은 키 누르기 이벤트를 캡처

$(document).keypress(function(e) { 
    switch(e.keyCode) { 
     case 37: 
      //left arrow pressed 
     break; 
     case 39: 
      //right arrow pressed 
     break; 
    } 
}); 
1

그냥 더 많은 아이디어를주는 작업을위한 배열로.

var panel_arr = new Array(); 
$(document).ready(function(e) { 

    $('.parallax-panel-wrapper').each(function(i, element){ 
     panel_arr.push($(this).attr("id")); 
    }); 

    var current_parallax_panel_no = 0; 
    $(document).keydown(function (evt) { 
     if (evt.keyCode == 40) { // down arrow 
      evt.preventDefault(); // prevents the usual scrolling behaviour 
      if(current_parallax_panel_no < (panel_arr.length-1)) current_parallax_panel_no++; 
      scrollByArrowKeys(1);    
     } else if (evt.keyCode == 38) { // up arrow 
      evt.preventDefault(); // prevents the usual scrolling behaviour 
      if(current_parallax_panel_no >= 1) current_parallax_panel_no--; 
      scrollByArrowKeys(0); 
     } 
    }); 

    function scrollByArrowKeys(add_more){ 
     scrollToThis = (($("#" + panel_arr[current_parallax_panel_no]).offset().top) + add_more ; // get element top 
     $.scrollTo(scrollToThis, 800);  
    } 

});