如何跳转到使用 JavaScript 放置在页面底部的特定 div?

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

How to jump to a specific div which placed bottom of page using JavaScript?

javascripthtmlinternet-explorerweb-applicationsweb

提问by Michael

I have a div which located at the bottom of the page:

我有一个位于页面底部的 div:

<div id="myDiv"></div>

I want to go to this div after performing of my JS-function. In other words, I want to have my url become myurl#myDivand to go to my div. But without reloading the page. How this can be done using JavaScript? Unfortunately I have not found a working solution for this issue. I am not using any JS-libraries and frameworks.

我想在执行我的 JS 功能后转到这个 div。换句话说,我想让我的网址成为myurl#myDiv并转到我的 div。但无需重新加载页面。如何使用 JavaScript 做到这一点?不幸的是,我还没有找到解决此问题的有效解决方案。我没有使用任何 JS 库和框架。

回答by dxh

To scroll to a particular element, use, scrollIntoView, supported by IE6+ and real browsers:

要滚动到特定元素,请使用scrollIntoView,IE6+ 和真实浏览器支持:

document.getElementById('myDiv').scrollIntoView();

Check window.location.hashon DOMReady, to see if there is a hash in the URL matching any element in your document.

检查window.location.hashDOMReady,查看 URL 中是否存在与文档中任何元素匹配的哈希值。

If there are #myDivlinks within the document, you would need to add onclicklisteners to them, perform the scroll manually, as per the code above, and return falseto avoid following the link to #myDiv.

如果#myDiv文档中有链接,您需要向onclick它们添加侦听器,按照上面的代码手动执行滚动,并return false避免跟随链接到#myDiv.

Demo

演示

回答by Robert K

Try setting the window's location to that of the ID. The browser will then scroll to that element.

尝试将窗口的位置设置为 ID 的位置。然后浏览器将滚动到该元素。

window.location.hash = '#myDiv';

回答by Ben Ripley

The scrollIntoView(true)method also accepts a parameter specifies whether to align to top (true) or bottom (false).

所述scrollIntoView(真)方法还接受参数指定是否对齐到顶部(真)或底部(假)。