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

时间:2015-11-24 11:57:16

标签: javascript jquery

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

谢谢!

2 个答案:

答案 0 :(得分:2)

更改您的选择器:

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

答案 1 :(得分:1)

你可以尝试像这样使用它

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

Css selector Test DEMO

Js selector Test DEMO

相关问题