【发布时间】: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