如何避免在某些内部链接上平滑滚动?
问题描述:
我使用最新评论here中的jQuery代码片段。在用户点击选项卡时,如何避免第二种情况下的这种行为?如何避免在某些内部链接上平滑滚动?
GOOD (it's working as it should):
<a href="#schedule">Schedule</a>
BAD (scrolls to the top of the page, which I dont want):
<a class="nav-link" data-toggle="tab" href="#tour" role="tab">TOUR</a>
<script>
$('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) {
var baseMinScrollTime = 500,
baseMaxScrollTime = 900;
var docHeight = $(document).height(),
triggerTop = $(this).offset().top,
targetTop = $target.offset().top;
var scrollProportion = (targetTop - triggerTop)/docHeight,
relativeTime = ((baseMaxScrollTime - baseMinScrollTime) * scrollProportion) + baseMinScrollTime,
// Create inverse relationship (quicker the further we scroll)
scrollTime = -1 * (1 - relativeTime);
$('html, body').animate({
scrollTop: targetTop - 10
}, scrollTime);
return false;
}
}
});
</script>
答
您可以提到,要避免在.not
部分从您的代码链接:
例如,如果你想避免命名为“家”的链接,然后使用:
$('a[href*="#"]')
:not('[href="#home"]')
:not('[href="#anotherLinkToSkip"]')
:not('[href="#yetAnother"]').click(function(){
//your logic here
})
:not
帮助您选择之前指定的所有内容,同时排除什么在它之后被指定。您可以附加更多not
块以指定更多要排除的元素。更多信息here
谢谢!我如何传递多个链接:#home,#one,#two,#three? – Jake
更新了我的答案。它现在应该适合你 –