如何将溢出的 div 滚动到某个主题标签(锚点)?
在我的网页上,我有一个溢出的 div(即带有垂直滚动条)。在 div 内部,我有带有 id 的锚点。当我将这些 id 之一放入 URL (mypage.html#id) 时,我希望 div(而不是页面)滚动到该锚点。
我该如何做到这一点,最好使用纯 JavaScript?如果它太复杂,我会使用 jQuery,但我不会在这个项目中将它用于其他任何用途。
On my webpage I have an overflowed div (i.e. with the vertical scrollbar). Inside the div, I have anchors with ids. When I put one of these ids in the URL (mypage.html#id), I want the div, not the page, to scroll to that anchor.
How do I do that, preferably with plain JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
完全没有理由不能将其转换为标准 javascript。
请注意,如果锚元素上有边距,则滚动将关闭。
There is no reason at all you can't convert this to standard javascript.
Note that the scroll will be off if there is a margin on the anchor element.
您是否尝试过在锚点上设置
focus()
?任何具有 tabindex 的 DOM 元素都是可聚焦的,并且任何具有焦点的元素都将被浏览器滚动到视图中。
Have you tried to set
focus()
on the anchor?Any DOM element with a tabindex is focusable, and any element which has focus will be scrolled into view by the browser.
这是一个纯 Javascript (ECMA 6) 解决方案,类似于 Ariel 的答案。
This is a pure Javascript (ECMA 6) solution, similar to Ariel's answer.
对于 2021 年使用几乎所有主流浏览器的用户,请使用
element.scrollIntoView()
。https://developer.mozilla.org/docs/Web/API/Element/滚动到视图
示例:
或使用 参数 -- Safari 或 Internet Explorer 不支持:
For those of you in nearly any major browser in 2021, use
element.scrollIntoView()
.https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView
Example:
or with Parameters -- Not supported in Safari or Internet Explorer: