繁体   English   中英

jQuery滚动到锚点-仅定位某些链接

[英]JQuery scroll to anchor - target only certain links

我在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>

效果很好,除了现在,所有超链接(例如,某些Bootstrap选项卡链接)都将触发脚本。

如何使以上脚本仅在以下链接中起作用:#mission,#vision,#strategy?

谢谢!

更改选择器:

$('a[href^="#"]')

或者您可以使用.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
});

请查看以下示例演示:

 $('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> 

你可以尝试像这样使用它

$('#mission[href*="#"]:not([href="#"]), #vision[href*="#"]:not([href="#"]), #strategy[href*="#"]:not([href="#"])')

CSS选择器测试演示

Js选择器测试DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM