在我的网页上,我有一个溢出的 div(即带有垂直滚动条)。在 div 内,我有带有 id 的锚点。当我将这些 id 之一放入 URL (mypage.html#id) 时,我希望 div 而不是页面滚动到该锚点。
我该怎么做,最好使用纯 JavaScript?如果它太复杂,我会使用 jQuery,但我不会在这个项目中将它用于其他任何事情。
在我的网页上,我有一个溢出的 div(即带有垂直滚动条)。在 div 内,我有带有 id 的锚点。当我将这些 id 之一放入 URL (mypage.html#id) 时,我希望 div 而不是页面滚动到该锚点。
我该怎么做,最好使用纯 JavaScript?如果它太复杂,我会使用 jQuery,但我不会在这个项目中将它用于其他任何事情。
$('.overflow').scrollTop($('#anchor').offset().top);
完全没有理由不能将其转换为标准 javascript。
请注意,如果锚元素上有边距,则滚动将关闭。
你试过设置focus()
锚吗?
任何具有 tabindex 的 DOM 元素都是可聚焦的,任何具有焦点的元素都将被浏览器滚动到视图中。
这是一个纯 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;
对于 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"
})