Waypoints JS和锚链接问题

时间:2016-02-17 01:59:17

标签: javascript scroll hyperlink scrolltop jquery-waypoints

我在页面上有很多文章,我使用Waypoints JS来触发scrollTop,并在文章进入视口时将文章捕捉到页面顶部,这样做很有效。 我在顶部还有一个固定的菜单,其中的哈希链接应该平滑滚动到页面的特定锚定部分。 问题是当我点击菜单上的链接时(让我们说第三篇文章):页面快速滚动到第三篇文章(假设),但随后它会自动滚动到第一篇文章,然后它再次下降到第三,然后到第二个,最后回到第三个。

显然,页面会保持弹跳,因为当页面向下滚动到锚点时,它会触发Waypoint。我怎样才能防止这种情况发生?我想在点击链接时禁用特定的Waypoints,然后在滚动后再次启用它,但我不确定这是最好的方法还是如何做到。

HTML

<ul>
<li id="btn1"><a href="#art1">Article 1</a></li>
<li id="btn2"><a href="#art2">Article 2</a></li>
<li id="btn3"><a href="#art3">Article 3</a></li>
</ul>
<article id="art1">content</article>
<article id="art2">content</article>
<article id="art3">content</article>

JS

//smooth scroll
$('a[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('body, html').animate({
                scrollTop: target.offset().top
            }, 500);
            return false;
        }
    }
});

//scroll snap to article 1
var waypoint = new Waypoint({
    element: document.getElementById('art1'),
    handler: function (direction) {
        if (direction === 'down') {
            $('html,body').animate({
                scrollTop: $('#art1').offset().top - 100
            }, 'slow');
        }
    },
    offset: '99%',
});

//scroll snap to article 2
var waypoint = new Waypoint({
    element: document.getElementById('art2'),
    handler: function (direction) {
        if (direction === 'down') {
            $('html,body').animate({
                scrollTop: $('#art2').offset().top - 100
            }, 'slow');
        }
    },
    offset: '99%',
});

//scroll snap to article 3
var waypoint = new Waypoint({
    element: document.getElementById('art3'),
    handler: function (direction) {
        if (direction === 'down') {
            $('html,body').animate({
                scrollTop: $('#art3').offset().top - 100
            }, 'slow');
        }
    },
    offset: '99%',
});

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我确定现在为时已晚,无法帮助你,但我遇到了同样的问题。

我希望像你一样在我的链接上方有一个偏移,但我意识到animate事件导致waypoints.js触发。

我非常聪明的解决方案是在你滚动的元素上,添加一个负边距和一个正面填充。

的CSS:

#art1,#art2,#art3{
  margin-top: -50px;
  padding-top: 75px;
}

并且JS使用常规location.hash,

window.location.hash = "#art1";