使用纯Javascript滚动到可滚动DIV内的元素 [英] Scrolling to a element inside a scrollable DIV with pure Javascript

查看:145
本文介绍了使用纯Javascript滚动到可滚动DIV内的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个溢出的div:滚动我在DIV中有一些隐藏的元素。单击页面上的按钮,我想让DIV滚动到DIV中的特定元素。

I have a div that has overflow: scroll and I have some elements inside the DIV that are hidden. On click of a button on the page, I want to make the DIV scroll to a particular element inside the DIV.

我如何实现这一目标?

推荐答案

你需要阅读你需要滚动到的div的 offsetTop 属性然后将该偏移设置为容器 div scrollTop 属性。将此函数绑定到您想要的事件:

You need to read the offsetTop property of the div you need to scroll to and then set that offset to the scrollTop property of the container div. Bind this function the event you want to :

function scrollToElementD(){
    var topPos = document.getElementById('inner-element').offsetTop;
    document.getElementById('container').scrollTop = topPos-10;
}

div {
    height: 200px;
    width: 100px;
    border: 1px solid black;
    overflow: auto;
}

p {
    height: 80px;
    background: blue;
}
#inner-element {
    background: red;
}

<div id="container"><p>A</p><p>B</p><p>C</p><p id="inner-element">D</p><p>E</p><p>F</p></div>
<button onclick="scrollToElementD()">SCROLL TO D</button>

function scrollToElementD(){
  var topPos = document.getElementById('inner-element').offsetTop;
  document.getElementById('container').scrollTop = topPos-10;
}

小提琴: http://jsfiddle.net/p3kar5bb/322/ (@rofrischmann提供)

Fiddle : http://jsfiddle.net/p3kar5bb/322/ (courtesy @rofrischmann)

这篇关于使用纯Javascript滚动到可滚动DIV内的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆