javascript 如何将溢出的 div 滚动到某个主题标签(锚点)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7513023/
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 do I scroll an overflowed div to a certain hashtag (anchor)?
提问by user323094
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.
在我的网页上,我有一个溢出的 div(即带有垂直滚动条)。在 div 中,我有带有 id 的锚点。当我将这些 id 之一放在 URL (mypage.html#id) 中时,我希望 div 而不是页面滚动到该锚点。
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.
我该怎么做,最好使用纯 JavaScript?如果它太复杂,我会使用 jQuery,但我不会在这个项目中将它用于其他任何事情。
采纳答案by Ariel
$('.overflow').scrollTop($('#anchor').offset().top);
There is no reason at all you can't convert this to standard javascript.
您完全没有理由不能将其转换为标准的 javascript。
Note that the scroll will be off if there is a margin on the anchor element.
请注意,如果锚元素上有边距,滚动将关闭。
回答by Martin Jespersen
Have you tried to set focus()
on the anchor?
你试过focus()
在锚上设置吗?
Any DOM element with a tabindex is focusable, and any element which has focus will be scrolled into view by the browser.
任何带有 tabindex 的 DOM 元素都是可聚焦的,任何具有焦点的元素都会被浏览器滚动到视图中。
回答by Caleb
This is a pure Javascript (ECMA 6) solution, similar to Ariel's answer.
这是一个纯 Javascript (ECMA 6) 解决方案,类似于 Ariel 的回答。
const overflow = document.querySelector('.overflow');
const anchor = document.getElementById('anchor');
// Get the bounding client rectangles for both
// the overflow container and the target anchor
const rectOverflow = overflow.getBoundingClientRect();
const rectAnchor = anchor.getBoundingClientRect();
// Set the scroll position of the overflow container
overflow.scrollTop = rectAnchor.top - rectOverflow.top;