jQuery smooth scroll positioning doesn't work

2019-08-08 20:24发布

问题:

I want to use a smooth scroll for my nav-links, but I am having a fixed nav, so I have to change the landing position a little bit. Now I found the answer in this forum and it looks like this:

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

        var target = this.hash;
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-100
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

The "top-100" should work, but it just doesn't... Does anybody have an idea? Thanks

回答1:

Use partseInt to always use the int value in browsers.

'scrollTop':  parseInt($target.offset().top,10);

parseInt() function parses a string argument and returns an integer of the specified radix or base.

Syntax

parseInt(string, radix);
  • string : The value to parse. If string is not a string, then it is converted to one.
  • radix : An integer between 2 and 36 that represents the radix of the above mentioned string.

jQuery

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

        var target = this.hash;
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop':  parseInt($target.offset().top,10)
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});