javascript 滚动到 div - jquery - 特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8082364/
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-10-26 02:11:56  来源:igfitidea点击:

scroll to div - jquery - specific position

javascriptjqueryscroll

提问by user947462

I am trying this code:

我正在尝试这个代码:

  function goToByScroll(id){

        id = id.replace("link", "");

        $('html,body').animate({
            scrollTop: $("#"+id).offset().top},
            'slow');
    }

    $("#sidebar > ul > li > a").click(function(e) {

        e.preventDefault();

        goToByScroll($(this).attr("id"));           
    });

The problem is that when i click in a specific element of list, the scroll go up to the top of the window. But in my case i have a fixed div in the top, so the content is hidden by this div. Well, I want stops the scroll before the div.

问题是,当我单击列表的特定元素时,滚动条会上升到窗口顶部。但在我的情况下,我在顶部有一个固定的 div,所以内容被这个 div 隐藏了。好吧,我想在 div 之前停止滚动。

any idea?

任何的想法?

demo

演示

回答by Kato

You need to give the top bar an id (e.g. id="header") and then subtract that from the scrollTop attribute:

您需要给顶部栏一个 id(例如 id="header"),然后从 scrollTop 属性中减去它:

$('html,body').animate({
    scrollTop: ($("#"+id).offset().top-$('#header').outerHeight(true))+'px'},
    'slow');

Here is a working example.

这是一个工作示例

回答by David Horák

function goToByScroll(id){

        id = id.replace("link", "");

        $('html,body').animate({
            scrollTop: ($("#"+id).offset().top - $("#YOUR_FIXED_DIV").height() ) },
            'slow');
    }

    $("#sidebar > ul > li > a").click(function(e) {

        e.preventDefault();

        goToByScroll($(this).attr("id"));           
    });