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

淺唱寂寞╮ 提交于 2019-12-06 22:31:11

问题


On my webpage I have an overflowed div (i.e. with the vertical scrollbar). Inside the div, I have anchors with ids. 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.

How do I do that, preferably with plain JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.


回答1:


$('.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.




回答2:


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.




回答3:


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;


来源:https://stackoverflow.com/questions/7513023/how-do-i-scroll-an-overflowed-div-to-a-certain-hashtag-anchor

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