[英]JQuery scroll to anchor - target only certain links
I have the following script that I implement on Sharepoint: 我在Sharepoint上实现了以下脚本:
<script>
$(function() {
$('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) {
$('#s4-workspace').animate({
scrollTop: target.offset().top
}, 2000);
return false;
}
}
});
});</script>
It works great, except that now, all hyperlinks, for example also some of the Bootstrap tab links will trigger the script. 效果很好,除了现在,所有超链接(例如,某些Bootstrap选项卡链接)都将触发脚本。
How can I make the above script work but only for the following links: #mission, #vision, #strategy ? 如何使以上脚本仅在以下链接中起作用:#mission,#vision,#strategy?
Thanks! 谢谢!
change your selector: 更改选择器:
$('a[href^="#"]')
or you can use .filter()
: 或者您可以使用
.filter()
:
$('a[href]').filter(function() {
var rg = /\#+\w/g; // this makes sure to select all the anchors with "href='#word'"
return rg.test(this.hash) === true;
}).click(function() {
// all the functionality as is
});
checkout the sample demo below:- 请查看以下示例演示:
$('a[href]').filter(function() { var rg = /\\#+\\w/g; return rg.test(this.hash) === true; }).css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='#what'>#what</a> <a href='http://hehehe.com'>http://</a> <a href='#how'>#How</a>
you can try use it like this 你可以尝试像这样使用它
$('#mission[href*="#"]:not([href="#"]), #vision[href*="#"]:not([href="#"]), #strategy[href*="#"]:not([href="#"])')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.