简体   繁体   English

jQuery滚动功能:按固定标头的高度偏移

[英]jQuery scroll function: offset by height of fixed header

I'm using the following jQuery click function to jump to various sections of a long scrolling page (by anchor ID) that also factors in-- and thus offsets by-- the height of a fixed navigation header: 我正在使用以下jQuery click函数跳转到长滚动页面的各个部分(通过锚点ID),这些部分也将固定导航标头的高度考虑在内,并因此偏移了:

$('#nav a').click(function(){
    var el = $(this).attr('href');
    var elWrapped = $(el);

    scrollToDiv(elWrapped,75);
    return false;

});
function scrollToDiv(element,navheight){
    var offset = element.offset();
    var offsetTop = offset.top;
    var totalScroll = offsetTop-navheight;

    $('body,html').animate({
    scrollTop: totalScroll
    }, 500);
}

This works very well, however, the only downside with this approach is I have to define an amount by which to offset the scroll from the page top-- in this case, by 75px, ie the height of the fixed header. 这种方法效果很好,但是,这种方法的唯一缺点是,我必须定义一个偏移量,以使滚动距页面顶部偏移-在这种情况下,偏移量为75px,即固定标题的高度。 For cases in which the height of the fixed header may change-- say for mobile via media query-- this height will likely be inaccurate, and the links won't offset by the correct amount of space. 对于固定标头的高度可能会发生变化的情况(例如,通过媒体查询进行移动),此高度可能不准确,链接也不会偏移正确的空间量。

Thus, I'm wondering how I might change/augment this function by calculating the actual height of the header and offset by that amount, plus say 10 additional pixels to account for section padding. 因此,我想知道如何通过计算标头的实际高度和偏移该量, 再加上 10个额外的像素来说明部分填充,来更改/增强此功能。

Thanks for any assistance here. 感谢您的协助。

You can get the height of the header when a button is clicked. 单击按钮时,可以获得标题的高度。

$('#nav a').click(function(){
    var el = $(this).attr('href');
    var elWrapped = $(el);
    var header_height = $('#header-id-goes-here').height() + 10;
    //var header_height = $('#header-id-goes-here').outerHeight(); You might need outerHeight if you have padding and borders

    scrollToDiv(elWrapped,header_height);
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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