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

被刻印的时光 ゝ 提交于 2019-12-05 04:11:19
$('.overflow').scrollTop($('#anchor').offset().top);

There is no reason at all you can't convert this to standard 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?

Any DOM element with a tabindex is focusable, and any element which has focus will be scrolled into view by the browser.

This is a pure Javascript (ECMA 6) solution, similar to Ariel's answer.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!