在我的网页上,我有一个溢出的div(即垂直滚动条)。在div内部,我有带有id的锚点。当我将其中一个id放入URL中(mypage.html#id)时,我希望该div而不是整个页面滚动到该锚点。如何做到这一点,最好使用纯JavaScript?如果太复杂,我会使用jQuery,但我在这个项目中没有为任何其他东西使用它。
$('.overflow').scrollTop($('#anchor').offset().top);
你完全可以将这个转换为标准的 JavaScript。
请注意,如果锚元素上有边距,则滚动将会偏移。
你尝试过在锚点上设置focus()
吗?
任何拥有tabindex属性的DOM元素都是可聚焦的,任何获得焦点的元素都会被浏览器滚动到视图中。
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;
对于2021年几乎所有主流浏览器的用户,可以使用element.scrollIntoView()
。
https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView
Element接口的scrollIntoView()方法滚动元素的父容器,使调用scrollIntoView()的元素对用户可见 - MDN Web Docs
示例:
var myEl = document.getElementById("child");
myEl.scrollIntoView()
或者使用参数 -- 不支持Safari或Internet Explorer:
myEl.scrollIntoView({
block: "center" // Start, center, end, or nearest. Defaults to start.
behavior: "smooth"
})