简体   繁体   English

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

[英]How do I scroll an overflowed div to a certain hashtag (anchor)?

On my webpage I have an overflowed div (ie with the vertical scrollbar).在我的网页上,我有一个溢出的 div(即带有垂直滚动条)。 Inside the div, I have anchors with ids.在 div 中,我有带有 id 的锚点。 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.当我将这些 id 之一放在 URL (mypage.html#id) 中时,我希望 div 而不是页面滚动到该锚点。

How do I do that, preferably with plain JavaScript?我该怎么做,最好使用纯 JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.如果它太复杂,我会使用 jQuery,但我不会在这个项目中将它用于其他任何事情。

$('.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.请注意,如果锚元素上有边距,滚动将关闭。

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 元素都是可聚焦的,任何具有焦点的元素都会被浏览器滚动到视图中。

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;

For those of you in nearly any major browser in 2021, use element.scrollIntoView() .对于 2021 年几乎所有主要浏览器中的那些人,请使用element.scrollIntoView()

https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user - MDN Web Docs Element 接口的 scrollIntoView() 方法滚动元素的父容器,以便调用 scrollIntoView() 的元素对用户可见 - MDN Web Docs

Example:例子:

var myEl = document.getElementById("child");
myEl.scrollIntoView()

or with Parameters -- Not supported in Safari or Internet Explorer:或带参数-- Safari 或 Internet Explorer 不支持:

myEl.scrollIntoView({
    block: "center" // Start, center, end, or nearest. Defaults to start.
    behavior: "smooth"
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM