簡體   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