jQuery smooth scroll positioning doesn't work

点点圈 提交于 2019-12-11 07:44:45

问题


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


来源:https://stackoverflow.com/questions/26969019/jquery-smooth-scroll-positioning-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!