jQuery scrollTop不能在同一个视口上工作

时间:2017-07-31 06:42:17

标签: javascript jquery html

我试图在相同的屏幕视口上跳过两个锚,但只要两个都可见,jquery只关注顶部的锚点。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="jump" id="1"></a>
<p>Content 1</p>
<a class="jump" id="2"></a>
<p>Content 2</p>
<a class="jump" id="3"></a>
<p>Content 3</p>

<style>
    .jump {
        margin-top: 300px;
        display: block;
    }

    body {
        padding-bottom: 500px;
    }
</style>

<script>
    var currentTarget = 0;
    var timer;
    var targets = new Array();
    $(".jump").each(function () {
        targets.push($(this).attr('id'));
    });

    $(function () {
        $(window).on('wheel', function (e) {
            clearTimeout(timer);
            var delta = e.originalEvent.deltaY;
            timer = setTimeout(function () {
                if (delta > 0) {
                    if (currentTarget < targets.length) {
                        $("html, body").animate({ scrollTop: $('#' + targets[currentTarget]).offset().top }, 1000);
                        console.log(targets[currentTarget]);
                        currentTarget++;

                        if (currentTarget >= targets.length) {
                            currentTarget = 0;
                        }
                    }
                }

                else {
                    console.log("Scroll Went Up");
                }
            }, 250);
        });
    });
</script>

是否有任何解决方法可以专注于两者。任何jQuery或JavaScript解决方案都被接受。

0 个答案:

没有答案