js定位div滚动条位置

2021-06-07  本文已影响0人  李仁平
如图: image.png

1.找到需要定位元素的位置,已Y轴为例,使用offsetTop找到距离父元素顶部的距离。
2.使用scrollTop属性使其父元素滚动到相应的位置,看下列代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function dw(){
      let [parentDoc,childDoc]= [document.querySelector('#fjd'),document.querySelector('.zjd')];
    parentDoc.scrollTop = childDoc.offsetTop - parentDoc.offsetHeight /2 ; //如果大于div高度使其居中
      childDoc.style.background = 'red'
    }
</script>
</head>
<body>
<button onclick="dw()">定位<button>
<div id="fjd" style="height:100px;overflow:auto;width: 200px;">
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div  >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div class="zjd" >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div>
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
        <div >
          找到了
        </div>
   </div>

</body>
</html>

对你有帮助的话点关注,不定时更新js有趣小知识。

上一篇 下一篇

猜你喜欢

热点阅读