发布时间:2025-12-09 11:53:26 浏览次数:1
scollTop
scrollTop 可以被设置为任何整数值,同时注意:
总结:元素发生溢出时可以设置scrollTop,设置的值为元素里内容向上滚动的不可见区域的高度
scollHeight
判定元素是否滚动到底
如果元素滚动到底,下面等式返回true,没有则返回false.
element.scrollHeight - element.scrollTop === element.clientHeight总结:当元素无溢出时为元素本身的高度,当元素发生溢出时为元素内容里面的总高度
例子:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>scroll</title> <style type="text/css"> #box{ width: 200px; height: 200px; border: 1px solid green; position: absolute; top: 350px; left: 0; } </style></head><body> <p style="position:absolute;top:0;bottom:0;left:0;right:0;overflow:scroll;height:300px;border: 1px solid red;"> <p style="font-size:20px;height:100px;border: 1px solid orange;"> 1 </p> <p style="font-size:20px;height:100px;border: 1px solid orange;"> 2 </p> <p style="font-size:20px;height:100px;border: 1px solid orange;"> 3 </p> <p style="font-size:20px;height:100px;border: 1px solid orange;"> 4 </p> <p style="font-size:20px;height:100px;border: 1px solid orange;"> 5 </p> </p> <p ></p> <p style="position:relative;top:350px;"> <button onClick="scrollToTop()">按钮1</button> <button onClick="read()">按钮2</button> </p> <script> console.log(document.getElementById('scrollBody').scrollHeight); //510 function scrollToTop(){ // 这里边可以写一些逻辑,比如偶数行一个一个的置顶,不如状态等于0的一个一个的置顶! document.getElementById('scrollBody').scrollTop = 200; console.log(document.getElementById('scrollBody').scrollTop) // 200 } function read(){ console.log(document.getElementById('box').scrollHeight); // 200 } </script></body></html>163721.html