scollTop
scrollTop 可以被设置为任何整数值,同时注意:
- 如果一个元素不能被滚动(例如,它没有溢出,或者这个元素有一个”non-scrollable”属性), scrollTop将被设置为0。
- 设置scrollTop的值小于0,scrollTop 被设为0
- 如果设置了超出这个容器可滚动的值, scrollTop 会被设为最大值.
总结:元素发生溢出时可以设置scrollTop,设置的值为元素里内容向上滚动的不可见区域的高度
scollHeight
判定元素是否滚动到底
如果元素滚动到底,下面等式返回true,没有则返回false.
复制代码
1
2element.scrollHeight - element.scrollTop === element.clientHeight
总结:当元素无溢出时为元素本身的高度,当元素发生溢出时为元素内容里面的总高度
例子:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58<!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> <div id="scrollBody" style="position:absolute;top:0;bottom:0;left:0;right:0;overflow:scroll;height:300px;border: 1px solid red;"> <div style="font-size:20px;height:100px;border: 1px solid orange;"> 1 </div> <div style="font-size:20px;height:100px;border: 1px solid orange;"> 2 </div> <div style="font-size:20px;height:100px;border: 1px solid orange;"> 3 </div> <div style="font-size:20px;height:100px;border: 1px solid orange;"> 4 </div> <div style="font-size:20px;height:100px;border: 1px solid orange;"> 5 </div> </div> <div id="box"></div> <div style="position:relative;top:350px;"> <button onClick="scrollToTop()">按钮1</button> <button onClick="read()">按钮2</button> </div> <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>
最后
以上就是大意小白菜最近收集整理的关于scrollTop和scrollHeight的全部内容,更多相关scrollTop和scrollHeight内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复