簡體   English   中英

平滑滾動以錨定偏移像素,除了一個特定的錨?

[英]Smooth scroll to anchor offset pixels, except one specific anchor?

我有一個UL導航,我已經使用了這種平滑滾動的jQuery:

$(document).ready(function () {
$(document).on("scroll", onScroll);

//smoothscroll
$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('a').each(function () {
        $('.nav').removeClass('active');
    })
    $('.nav').addClass('active');

    var target = this.hash,
        menu = target;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-59
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});
});

它達到了-59像素,這是我需要做的,除了一個錨點之外,是否可以添加一行代碼,寫上“ X類除外”之類的東西? jQuery新手在這里;)

任何幫助將是巨大的,謝謝。

在click事件中,您既可以訪問單擊的nav元素(this),也可以訪問要滾動到的目標($ target)。 您可以查看其中任意一個以確定是否需要抵消-59以外的某個數量。

如果情況很少,則需要使用其他偏移量,可以執行以下操作:

var offset = -59;
if ($(this).attr(href)=="#something") offset=-100; //or whatever special offset you need

並更改此行:

'scrollTop': $target.offset().top-59

對此:

'scrollTop': $target.offset().top+offset

如果您想要更通用的解決方案並可以訪問html,則可以將data屬性放在<a>或目標元素上,例如

<a href="#something" data-scroll-offset=-100></a>

然后,類似於第一種方法:

var offset=-59;
if ($(this).attr("data-scroll-offset")!==null) offset=$(this).attr("data-scroll-offset");

如果在目標元素上,它將是$ target而不是$(this)


如果要完全排除某個錨,可以將其從錨選擇器中刪除。 代替這個

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

像這樣只排除某個錨點:

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

或排除具有特定類別的所有錨點,例如:

$('a[href^="#"]:not(.excludeMe)')

暫無
暫無

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

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