[英]Disable Smooth Scrolling on Non-Anchor Hash Link?
I have some jquery for smooth scrolling: 我有一些jQuery可以平滑滚动:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 1400);
});
Which works fine, except that I have some tabs on the page that use a hash link also. 效果很好,除了页面上还有一些使用哈希链接的标签。 When you click each tab, the page scrolls to the top of the screen. 单击每个选项卡时,页面将滚动到屏幕顶部。
Is there a way to make this smooth scroll work, only when a specific anchor is added to the hash (like /#features) and not work when it is a hash only (like /#) 只有在将特定锚添加到哈希(例如/#features)时,才有办法使这种平滑滚动工作,而仅当它是哈希(例如/#)时不起作用。
You can add a :not()
selector to eliminate href="#"
from triggering your click
event. 您可以添加:not()
选择器,以消除href="#"
触发click
事件。
$(document).on('click', 'a[href^="#"]:not([href=#])', function(event) { console.log("Clicked"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#">Hash Only</a> <a href="#Anchor1">Anchor 1</a> <a href="#Anchor2">Anchor 2</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.