javascript - 如何在js中滚动多个ID的页面

标签 javascript jquery scrolltop

请检查我做了什么http://jsfiddle.net/dUVmh/1/ .

关于我想要实现的动画是:

当您第一次向下滚动页面时,窗口滚动到#green DIV。之后,如果您再次向下滚动窗口,滚动到 #yellow DIV 并在向上滚动时进行相同操作(从 #yellow 到 #green)。

关于问题: 您可以看到它卡在#green DIV 上的动画。

$(window).scroll(function(){
    if($(this).scrollTop() > 0) {
        $("html, body").animate({ scrollTop: $('#green').offset().top }, 1000);
    }
    else if($(this).scrollTop() > 1000) {
        $("html, body").animate({ scrollTop: $('#yellow').offset().top }, 1000);
    }
    else{
         $("html, body").animate({ scrollTop: $('#red').offset().top }, 1000);
    }

});

我在 JS 方面没有太多经验。

谢谢我提前:)

最佳答案

这是一个有趣的问题。

此解决方案将 div 放入数组中,并记住上次滚动到的元素的数组索引。一旦触发滚动事件,它就会检查新的scrollTop是否高于或低于当前div顶部偏移量,并相应地移动到数组中的下一个或上一个div。

此解决方案允许您拥有多个 div。我尝试消除快速滚动时出现的闪烁,但我认为唯一的方法是在动画期间禁用滚动条。

http://jsfiddle.net/dUVmh/35/

$(function() {
    var divs = [],
        body = $('body, html'),
        currentDiv = 0,
        timeout;

    $('div').each(function() {
        divs.push($(this));
    });

    // we only need to capture the first scroll event triggered and then
    // add another listener once we have done our animation
    var scrollListen = function() {
        $(window).one('scroll', function() {
            doScroll($(this).scrollTop());
        });
    };

    // Without the timeout, the scroll event would be triggered again too soon
    var scrollEnd = function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            scrollListen();
        }, 10);
    };

    // checks if the scroll direction was up and down and animates
    // the body scrollTop to the next or previous div
    var doScroll = function(scrollTop) {
        var direction = scrollTop - divs[currentDiv].offset().top;

        if (direction > 0 && currentDiv + 1 < divs.length) {
            nextDiv = currentDiv + 1;
        } else if (currentDiv - 1 > -1) {
            nextDiv = currentDiv - 1;
        }

        if (currentDiv === nextDiv) {
            scrollEnd();
        }

        body.animate({
            scrollTop: divs[nextDiv].offset().top
        }, 1000, function() {
            currentDiv = nextDiv;
            scrollEnd();
        });
    };

    scrollListen();
});

编辑:Firefox的scrollTop需要在html上进行更改,而不是在正文上进行更改。还修复了 Firefox 一次多次调用scrollListen 的问题。

关于javascript - 如何在js中滚动多个ID的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109315/

相关文章:

javascript - 异步还是同步?我该如何处理这些API调用?

javascript - 如何让 html5 颜色选择器在 IE 中工作?

Javascript 变量不保留值

javascript - 玩 super 卷轴中的固定元素

jquery - 滚动到 Div/元素顶部

javascript - .closest() 在 CSS 中

javascript - 如何使用 Handlebars 模板动态加载不同的部分?

javascript - 如何显示当前文件上传的缩略图和预览

javascript - CSS3 : nested menu in full screen overlay

javascript - 动画 ScrollTop 用于单页 anchor 的侧面导航