如何滚动到div内的元素

如何滚动到div内的元素

本文介绍了如何滚动到div内的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个滚动的 div ,我想点击它时会有一个链接,它会强制这个 div 滚动查看里面的元素。
我写它的JavasSript是这样的:

  document.getElementById(chr).scrollIntoView(true); 

但是在滚动 div 如何解决这个问题?



我想这样说

  MyContainerDiv.getElementById(CHR).scrollIntoView(真); 


解决方案

您需要获取元素的顶部偏移量'd喜欢滚动到视图中,相对于其父(滚动div容器):

  var myElement = document.getElementById( 'element_within_div'); 
var topPos = myElement.offsetTop;

变量topPos现在设置为滚动div的顶部和您希望的元素之间的距离(像素)。

现在我们告诉div使用 scrollTop

  document.getElementById('scrolling_div')。scrollTop = topPos; 

如果你使用的是JS框架的原型,你可以做同样的事情: / p>

  var posArray = $('element_within_div').placeOffset(); 
$('scrolling_div')。scrollTop = posArray [1];

同样,这会滚动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.I wrote its JavasSript like this:

document.getElementById(chr).scrollIntoView(true);

but this scrolls all the page while scrolling the div itself.How to fix that?

I want to say it like that

MyContainerDiv.getElementById(chr).scrollIntoView(true);
解决方案

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):

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).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

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内的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 14:18