jQuery 页面加载时滚动到

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

Scroll to when page load

jquerygoogle-chromescrollto

提问by Alireza

i got a jquery code from this link (end of page): How to scroll to top of page with JavaScript/jQuery?

我从这个链接(页面末尾)得到了一个 jquery 代码: 如何使用 JavaScript/jQuery 滚动到页面顶部?

Why don't you just use some reference element at the very beginning of your html file, like

为什么不在 html 文件的开头使用一些参考元素,例如

<div id="top"></div>

and then, when the page loads, simply do

然后,当页面加载时,只需执行

$(document).ready(function(){

    top.location.href = '#top';

});

If the browser scrolls after this function fires, you simply do

如果浏览器在此功能触发后滚动,您只需执行

$(window).load(function(){

    top.location.href = '#top';

});

now, everything is working but not in google chrome! how i can fix this code for google chrome?and how i can add a some animation to this code? like scroll speed or fast, slow etc...

现在,一切正常,但不是在谷歌浏览器中! 我如何为谷歌浏览器修复此代码?以及如何向此代码添加一些动画?像滚动速度或快,慢等...

回答by lewiguez

If you're using jQuery, you can use scrollTopto scroll. It's a method, but it can be animated too. Here is the documentation: jQuery API Documentation for scrollTop

如果您使用 jQuery,则可以使用scrollTop滚动。这是一种方法,但它也可以动画化。这是文档:scrollTop 的 jQuery API 文档

You can use it like so:

你可以像这样使用它:

$("html,body").scrollTop(0);

Or for animating:

或用于动画:

$("html,body").animate({scrollTop: 0}, 1000);

You could set this in any event handler:

您可以在任何事件处理程序中设置它:

$(document).ready(function()
{
     $("html,body").animate({scrollTop: 0}, 1000);
}

Or:

或者:

$(window).load(function()
{
     $("html,body").animate({scrollTop: 0}, 1000);
}

回答by cburyta

(I'd recommend the answer lewiguez gave in practice, but still not sure why your method didn't work in google chrome.)

(我推荐 lewiguez 在实践中给出的答案,但仍然不确定为什么你的方法在 google chrome 中不起作用。)

That seems to be working for me, I'm not sure about the window load though. I tested the actual "top.location.href" line though on click of a link.

这似乎对我有用,但我不确定窗口负载。我通过单击链接测试了实际的“top.location.href”行。

$('#bottomlink').click(function(){
  top.location.href="#top";
  return false;
});

This is near the top of the page.

这是在页面顶部附近。

<p id="top">lorem ipsum</p>

And this is the link at the bottom of the page.

这是页面底部的链接。

<a id="bottomlink" href="#">Bottom Link</a>