如何避免在某些内部链接上平滑滚动?
How to avoid smooth scrolling on certain internal links?
我正在使用最近评论 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
部分提及要避免的 link:
例如,如果您想避免 link 命名为 "home",则使用:
$('a[href*="#"]')
:not('[href="#home"]')
:not('[href="#anotherLinkToSkip"]')
:not('[href="#yetAnother"]').click(function(){
//your logic here
})
:not
可以帮助您 select 在它之前指定的所有内容,同时排除在它之后指定的内容。您可以附加更多 not
块以指定要排除的更多元素。更多信息 here
我正在使用最近评论 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
部分提及要避免的 link:
例如,如果您想避免 link 命名为 "home",则使用:
$('a[href*="#"]')
:not('[href="#home"]')
:not('[href="#anotherLinkToSkip"]')
:not('[href="#yetAnother"]').click(function(){
//your logic here
})
:not
可以帮助您 select 在它之前指定的所有内容,同时排除在它之后指定的内容。您可以附加更多 not
块以指定要排除的更多元素。更多信息 here