jQuery 在页面加载时移动到锚点位置

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

jQuery move to anchor location on page load

jqueryscrollanchor

提问by scferg5

I have a simple page setup such as:

我有一个简单的页面设置,例如:

<div id="aboutUs">
  About us content...
</div>
<div id="header">
  Header content...
</div>

When the page loads, I need the page to automatically scroll down (no animation needed) to #header, so the user cannot see the About Us div unless they scroll up.

当页面加载时,我需要页面自动向下滚动(不需要动画)到#header,因此用户无法看到关于我们的 div,除非他们向上滚动。

#aboutUshas a fixed height, so there isn't any need for any variables to determine the height or anything... if that's even needed.

#aboutUs有一个固定的高度,所以不需要任何变量来确定高度或任何东西......如果甚至需要的话。

I came across this other questionand tried to modify some of the answers for my situation, but nothing seemed to work.

我遇到了另一个问题,并试图根据我的情况修改一些答案,但似乎没有任何效果。

Any help would be appreciated.

任何帮助,将不胜感激。

回答by dknaack

Description

描述

You can do this using jQuery's .scrollTop()and .offset()method

您可以使用 jQuery.scrollTop().offset()方法来做到这一点

Check out my sample and this jsFiddle Demonstration

查看我的示例和这个jsFiddle 演示

Sample

样本

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

更多信息

回答by Naveed

Did you tried JQuery's scrollTomethod? http://demos.flesler.com/jquery/scrollTo/

你试过JQuery的scrollTo方法吗?http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

或者您可以扩展 JQuery 并添加您的自定义mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

然后你可以像这样调用这个方法:

$("#header").scrollToMe();

回答by Chris Pietschmann

Put this right before the closing Body tag at the bottom of the page.

将其放在页面底部的结束 Body 标记之前。

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

实际上不需要 jQuery。