【问题标题】:Waypoints JS and anchor links issueWaypoints JS 和锚链接问题
【发布时间】:2016-02-17 01:59:17
【问题描述】:

我在一个页面上有一堆文章,我正在使用 Waypoints JS 来触发一个 scrollTop 并在文章进入视口时将其捕捉到页面顶部,这很好用。 我在顶部还有一个带有哈希链接的固定菜单,这些链接应该可以平滑滚动到页面的特定锚定部分。 问题是当我点击菜单上的链接时(比如说第三篇文章):页面快速滚动到第三篇文章(如预期的那样),但随后它自动向上滚动到第一篇文章,然后向下滚动到再次第三次,然后上升到第二次,最后回到第三次。

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

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%',
});

感谢您的帮助。

【问题讨论】:

    标签: javascript scroll hyperlink scrolltop jquery-waypoints


    【解决方案1】:

    我确定这对您来说太晚了,但我遇到了同样的问题。

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

    我非常简单的解决方案是在您滚动到的元素上,添加负边距和正填充。

    css:

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

    对于 JS,使用常规 location.hash,

    window.location.hash = "#art1";
    

    【讨论】:

      猜你喜欢
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多