js定位div滚动条位置

2,060 阅读1分钟

如图: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有趣小知识。