.animate()工作不止一次

时间:2014-07-18 14:28:25

标签: javascript jquery html jquery-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>

2 个答案:

答案 0 :(得分:0)

$('html,body').offset().top + $("SECTION#1").height()始终返回相同的值。所以这就是它无法正常工作的原因。

作为解决方案,请尝试$(document).offset().top或使用类似的计数器:

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

答案 1 :(得分:0)

在这里,您告诉浏览器每次都滚动到同一个地方:

(...) {scrollTop:$(&#39; html,body&#39;)。offset()。top + $(&#34; SECTION#1& #34;)。height()} (...)

最安全的滚动方式是将转到给定元素的顶部。通过这种方式,即使您为元素添加一些余量(也不会添加到高度),它也会起作用。

我假设您的代码是缩减,而不是整页。

$(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 '#'+

   });

})