Javascript JQuery 从浏览器顶部滚动到偏移量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3991002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:02:44  来源:igfitidea点击:

JQuery Scroll to Offset from top of browser?

javascriptjquery

提问by Jezthomp

I have the following scroll script, which scrolls round the page fine, works exactly how i want it too.

我有以下滚动脚本,它可以很好地滚动页面,也完全符合我的要求。

$(function(){
    $('a[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) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
});

However, i need it to ignore the top say 200px as i have a fixed header at the top of the page that the content scrolls behind.

但是,我需要它忽略顶部说 200px,因为我在页面顶部有一个固定的标题,内容滚动到后面。

Meaning that when i scroll to top it scrolls the content to behind the fixed header so i cannot see it, so i need it to scroll to just below the header.. so to treat the bottom of the header as the top of the browser i suppose....

这意味着当我滚动到顶部时,它会将内容滚动到固定标题的后面,所以我看不到它,所以我需要它滚动到标题的正下方..所以将标题的底部视为浏览器的顶部我认为....

Can this be done as it would be very handy?

可以这样做吗,因为它会非常方便吗?

Many thanks for any help

非常感谢您的帮助

回答by tinifni

Would something like this work?

这样的东西会起作用吗?

var targetOffset = $target.offset().top - 200;

Or grab the height of the header element for the extra offset.

或者获取标题元素的高度以获得额外的偏移量。

var targetOffset = $target.offset().top - $("element").outerHeight(true);

回答by Mulki

You could use something like this if condition on ur code to do that

如果你的代码有条件,你可以使用这样的东西来做到这一点

//check if the absolute position is below header
if ($('#IdOfTheScrollElement').position().top >= 200 ){
//scroll
}
else {
//do nothing
}

回答by Chaos

The Code is fine, you just need to remove the height of your fixed header here, for example if it's 200px. it will work perfectly.

代码很好,您只需要在此处删除固定标题的高度,例如如果它是 200px。它会完美地工作。

 $('html,body').animate({scrollTop: (targetOffset().top)-200}, 1000);

You can also check this when a button is clicked

您也可以在单击按钮时进行检查

$(function() {

$('a[href*=#]:not([href=#])').click(function() {

    // Check height of the header and padding
    var header_height = $('.header').outerHeight();

Remove it from your offset

从您的偏移量中删除它

$('html,body').animate({scrollTop: (targetOffset().top) - header_height }, 1000);