簡體   English   中英

jQuery平滑滾動-如何不以一個錨鏈接為目標?

[英]JQuery Smooth Scroll - How to not target one anchor link?

我正在使用以下Jquery來平滑滾動頁面上的錨鏈接。 我有一個我不希望定位的鏈接-有一種方法可以編輯代碼以定位除一個錨定鏈接以外的所有鏈接?

我也復制了下面的鏈接。

var $root = $('html, body');

$(document).on('click', 'a[href^="#"]', function (event) {
  event.preventDefault();

  $('html, body').animate({
      scrollTop: $($.attr(this, 'href')).offset().top
  }, 500);
}); 

這是我不想被稱為的鏈接:

<a href="#" class="cn-set-cookie button wp-default">Ok</a>

這些是我確實想通過函數調用的鏈接:

<li class="key-details"><a href="#key-details-scroll">Key Information</a></li>
<li class="about"><a href="#about">About the Service</a></li>
<li class="health"><a href="#health-experience">Health Experience</a></li>

給它上課...說“ no_smooth”。

<a href="#" class="cn-set-cookie button wp-default no_smooth">Ok</a>

然后使用:not()排除它。

$(document).on('click', 'a[href^="#"]:not(".no_smooth")', function (event) {
  //... Rest unchanged
});

解決方案 1:

var $root = $('html, body');

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    if($(this).hasClass('wp-default')) return;// with this line of code you'll prevent to call function on "OK" anchor
    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});


解決方案 2:
或者,您可以通過以下方式修改代碼:

var $root = $('html, body');

$(document).on('click', 'a[href^="#"]:not(".wp-default")', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});


解決方案 3:
另一種方法是對href使用其他屬性:

<a href="javascript:void(0);" class="cn-set-cookie button wp-default">Ok</a>

javascript:void(0); 將阻止此錨調用任何js函數。

PS :您可以使用此類名稱以及cn-set-cookie代替wp-default也可以將類設置為那些您不想使它們調用的滾動平滑的錨。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM