Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 如何滚动到div中的元素?(How to scroll to an element inside a div?)

I have a scrolled div and I want to have a link when I click on it it will force this div to scroll to view an element inside.(我有一个滚动的div ,当我单击它时我想要一个链接,它将迫使该div滚动以查看其中的元素。)

I wrote its JavasSript like this:(我这样写它的JavasSript:) document.getElementById(chr).scrollIntoView(true); but this scrolls all the page while scrolling the div itself.(但这会在滚动div本身的同时滚动所有页面。) How to fix that?(如何解决?) I want to say it like that(我想这样说) MyContainerDiv.getElementById(chr).scrollIntoView(true);   ask by Amr Elgarhy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):(您需要获取要滚动到视图中的元素相对于其父元素(滚动div容器)的顶部偏移量:)

var myElement = document.getElementById('element_within_div'); var topPos = myElement.offsetTop; The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).(现在,变量topPos设置为滚动div的顶部与希望显示的元素之间的距离(以像素为单位)。) Now we tell the div to scroll to that position using scrollTop :(现在,我们告诉div使用scrollTop滚动到该位置:) document.getElementById('scrolling_div').scrollTop = topPos; If you're using the prototype JS framework, you'd do the same thing like this:(如果您使用原型JS框架,则可以执行以下操作:) var posArray = $('element_within_div').positionedOffset(); $('scrolling_div').scrollTop = posArray[1]; Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).(再次,这将滚动div,以便您希望看到的元素恰好在顶部(或者,如果不可能的话,请尽可能向下滚动以使其可见)。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...