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,以便您希望看到的元素恰好在顶部(或者,如果不可能的话,请尽可能向下滚动以使其可见)。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…