Javascript 如何将焦点设置在页面顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2956828/
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
how to set focus on top of the page
提问by vakas
How do I set focus to the top of a page?
如何将焦点设置到页面顶部?
回答by Gotter
回答by Sarin J S
Check this similar question. This has so many answers which gives you different ways to do it
Below are the mainly suggested methods,
以下是主要推荐的方法,
Javascript to scroll to top coordinate.
用于滚动到顶部坐标的 Javascript。
window.scrollTo(0,0);
Syntax is,
语法是,
window.scrollTo(x-coord, y-coord);
scroll up using jquery,
使用 jquery 向上滚动,
$("html, body").animate({ scrollTop: 0 }, "slow");
navigate/scroll to a particular element using javascript,
使用 javascript 导航/滚动到特定元素,
<div id="jump_to_me">
blah blah blah
</div>
<a target="#jump_to_me">Click Here To Destroy The World!</a>
simple javascript way to focus on top,
专注于顶部的简单 javascript 方式,
window.location = '#'
回答by Yanick Rochon
document.location.href = "#";
will scroll back up, but will also add a '#' to your URL, but given the question, I could have just answered
将向上滚动,但也会在您的 URL 中添加一个“#”,但鉴于这个问题,我本可以回答
functionToSetFocusOnTopOfPage();
and it would be just as good
它也一样好
回答by Starx
It would be helpful if you write a little so that we can understand your problem.
如果您写一点,以便我们了解您的问题,将会很有帮助。
A very easy way is linking to class or id on a page.
一个非常简单的方法是链接到页面上的类或 id。
For example this page "page.html"
例如这个页面“page.html”
<body>
<div id="top"> ..................Content................</div>
<div id="otherdiv">........................</div>
</body>
then if you need to focus on top, send a link like "page.html#top" the page will automatically focus on top
那么如果你需要关注顶部,发送一个像“page.html#top”这样的链接页面会自动关注顶部
or if you want to stick to javascript then do this
或者如果你想坚持使用 javascript 然后这样做
document.location.href = '#top'; //to send it to the top
But I would say use simple html anchor to go to top like
但我会说使用简单的 html 锚点去顶部
<a href="#top">Back to Top</a>
<a href="#top">Back to Top</a>

