如何将溢出的div滚动到某个#标签(锚点)?

问题描述 投票:8回答:3

在我的网页上,我有一个溢出的div(即垂直滚动条)。在div里面,我有ids的锚点。当我在URL(mypage.html#id)中放入其中一个ID时,我希望div而不是页面滚动到该锚点。

我该怎么做,最好使用纯JavaScript?如果它太复杂了,我将使用jQuery,但我不会在这个项目中使用它来做任何其他事情。

javascript anchor hashtag
3个回答
9
投票
$('.overflow').scrollTop($('#anchor').offset().top);

完全没有理由你不能将它转换为标准的javascript。

请注意,如果锚元素上有边距,则滚动将关闭。


5
投票

你试过在锚上设置focus()吗?

具有tabindex的任何DOM元素都是可聚焦的,任何具有焦点的元素都将被浏览器滚动到视图中。


1
投票

这是一个纯粹的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;
© www.soinside.com 2019 - 2024. All rights reserved.