简体   繁体   中英

Smooth scroll to anchor offset pixels, except one specific anchor?

I have a UL nav, I've got this smooth scroll jQuery working:

$(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);
    });
});
});

it goes to -59 pixels, which is what I need it to do for all but one anchor, is there a way I can add a line of code that says 'except class X' or something? Jquery novice here ;)

Any help would be great, thanks.

On your click event, you have access to both the nav element you clicked on (this) and the target you are scrolling to ($target). You can look at either of those to determine that you need to offset by some amount other than -59.

If you have very few cases you need to have a different offset for, you can do this:

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

And change this line:

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

to this:

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

If you want a more versatile solution and have access to the html, you can put a data attribute on either the < a> or the target element, like

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

And then, similarly to the first method:

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

If it were on the target element, it would be $target instead of $(this)


If you want to exclude a certain anchor entirely, you could remove it from the anchor selector. Instead of this

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

Exclude only a certain anchor like so:

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

or exclude any anchors with a certain class like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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