2014-07-18 4 views
0

"아래쪽 화살표"이 포함 된 다음 코드를 작성했습니다.이 코드를 누르면 페이지를 한 번에 한 섹션 아래로 스크롤 할 수 있습니다. 한 번만 작동하는 것처럼 보입니다 - 내가 잘못한 것을 누군가 볼 수 있습니까?.animate()가 두 번 이상 작동하지 않습니다

참고 :몸 높이 의도적 내 요구를 지원하기에 충분하다.

<STYLE> 
*{margin:0;padding:0} 
body{height:1000px; width:2000px; overflow:hidden;} 
SECTION{border: 1px dashed black; height:100px; width:300px; overflow:auto; float:top;} 
.int{position:relative; width:100px;height:100px;background:#fff; float:left;} 
</STYLE> 

<SECTION ID="1">1</SECTION> 
<SECTION ID="2">2</SECTION> 
<SECTION ID="3">3</SECTION> 

<SCRIPT SRC="jquery.js"></SCRIPT> 
<SCRIPT SRC="jquery.easing.1.3.min.js"></SCRIPT> 

<SCRIPT> 

function scroll($dir){ 
    // This is the main scroll function 
    if($dir=="down") 
     $('html,body').stop().animate({ 
      scrollTop: $('html,body').offset().top + $("SECTION#1").height() 
     }, 800, "easeInQuart"); 
} 

// Function which controls key-based navigation 
$(document).on("keydown", function(e) { 
    if(e.which == 40) scroll("down"); 
}); 

</SCRIPT> 
+0

jsfiddle –

답변

0

$('html,body').offset().top + $("SECTION#1").height() 항상 같은 값을 반환합니다. 그래서 그것이 작동하지 않는 이유입니다.

솔루션으로, $(document).offset().top을 시도하거나 지금과 같은 카운터 사용

(...) {: 당신은 같은 장소 매번로 이동하는 브라우저를 말하고있다 여기

var currentPage = 0; 
function scrollDown() { 
    $(...).animate({scrollTop: pageHeight * (currentPage++)}); 
} 
0

을 scrollTop :... $ ('HTML, 몸')) (오프셋 상단 + $ ("제 # 1") 높이()} (...)

scrol하는 가장 안전한 방법 내가 주어진 요소의 상단에 이되도록하는 것입니다. 이렇게하면 요소에 약간의 여백을 추가하더라도 작동합니다 (높이에 추가되지 않음).

귀하의 코드는 전체 페이지가 아닌 축소 된 것으로 가정합니다.

$(function(){ // document ready 

    // var 'current' assumes that page may load with a hash pointing to a specific section. 
    // Otherwise its on section #1 
    // var 'limit' is the fixed amount of sections that you provided. 
    // you may (and problably should) use a list instead of 'id-numbered' sections and get its length. Like: $('#your_list li').length 
    var current = window.location.hash || 1, 
     limit = 3; 

    function scrollTo(element){ 

     $('html, body').animate({ 
      scrollTop: ($(element).offset().top) 
     }, 800, 'easeInQuart'); 

     console.log('scrolling to $('+element+').offset().top'); 

    } 

    $(document).on("keydown", function(e) { 
     switch (true) { 
      case (e.which === 40 && (current < limit)): // 40 = down key 
       current += 1 ; 
       break; 
      case (e.which === 38 && (current > 1)): // 38 = up key 
       current -= 1 ; 
       break; 
     } 

     scrollTo('#'+current); // must prepend id selector '#'+ 

    }); 

}) 
관련 문제