jQuery滚动太远了

时间:2014-07-10 01:33:06

标签: jquery twitter-bootstrap

我知道有人问过,但我不确定如何将答案应用到我的网站。我在BOOTSTRAP中有一个固定的导航栏,滚动到某个div只是一个BIT太远,所以div的顶部被固定的导航阻挡。

//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

1 个答案:

答案 0 :(得分:3)

$($anchor.attr('href')).offset().top部分用于计算页面向下滚动身体的距离。

您可以在此数字中添加或减去以更好地对齐事物。

您可以测量导航的高度并使用该数字从offset().top值中减去

$(function() {
    var navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - navHeight
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

然后,您也可以在窗口调整大小时更新此值,这样如果您的导航更改高度(例如,如果发生换行),则会更新您的固定值

$(function() {
    var navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
    $(window).bind('resize', function(){
        navHeight = $('#fixedNav').outerHeight(); // adjust this for your nav id
    });
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - navHeight
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

如果你想对resize事件解决方案进行更新,我还建议实现某种类型的throttler(例如,它每隔100ms只更新一次高度值,而不是每次事件触发器),这应该会提升性能。看看Ben Almans Throttle/Debounce

之类的东西
相关问题