javascript - 我怎样才能在这个脚本上添加类

标签 javascript jquery scrolltop

我在我的项目中使用了这个脚本,一个带滚动的单页。现在我的问题是每次页面滚动到确切的部分时标题总是被我的固定菜单隐藏。下面是脚本

$('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
        || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
           if (target.length) {
             $('html,body').animate({
                 scrollTop: target.offset().top
            }, 1500,'easeInOutExpo');
            return false;
        }
    }
});

希望大家能帮帮我。 非常感谢!

最佳答案

You'll need to take into account the height of the fixed header when applying scrollTop

如果我的评论不够清楚,请尝试这个。

$('a[href*=#]:not([href=#])').click(function() {
// does the pathname of this link match that of the current location.pathname?
var activeLink = (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,''));

if (activeLink || location.hostname == this.hostname) {

    var target = $(this.hash);

    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

    if (target.length) {

         // here we will take into account the height of #navbar
         var offset = target.offset().top + $('#navbar').height();

        $('html,body').animate({
             scrollTop: offset // apply our new offset
        }, 1500,'easeInOutExpo');

        return false;
    }
}

});

关于javascript - 我怎样才能在这个脚本上添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27919203/

相关文章:

javascript - 使用 Express 从提交中删除 .gitignore API key 的最佳实践是什么?

javascript - Node 定义我需要在模块中使用的唯一变量

jquery - Primefaces 6.0 对话框架和框架集

javascript - 单击按钮滚动到带有类的 div

javascript - 强制内部 iframe 内容在页面加载时滚动到顶部

javascript - 将元素作为变量传递给函数

javascript - 有没有更好的方法来处理 laravel 和 vue js 的 axios 错误

javascript - 如何在显示之前的 Jquery keyup 事件期间从输入中删除空格

javascript - jQuery 滑动切换和淡入问题

javascript - WebKit 有裁剪错误吗?