100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Element属性 :获取 设置元素滚动距离 scrollHeight scrollTop scrollLeft属性详解

Element属性 :获取 设置元素滚动距离 scrollHeight scrollTop scrollLeft属性详解

时间:2023-10-19 00:08:23

相关推荐

Element属性 :获取 设置元素滚动距离 scrollHeight scrollTop  scrollLeft属性详解

Element.scrollHeight - Web API 接口参考 | MDN

Element.scrollHeight这个只读属性是一个元素内容高度的度量,包括由于溢出导致的视图中不可见内容。

计算公式:scrollHeight =内容高(包括溢出的)+ paddingTop + paddingBottom

(1)没有垂直滚动条的情况下,scrollHeight和clientHeight相等:

​<style>* {margin: 0;}#father {box-sizing: border-box;width: 150px;height: 150px;padding: 20px;border: 10px solid green;background: red;overflow: auto;}#son {width: 50px;height: 50px;background: blue; line-height: 50px;text-align: center;}</style><body><div id="father"><div id="son">son</div></div></body><script>var father = document.getElementById("father");// 没有垂直滚动条时,scrollHeight和clientHeight相等console.log(father.clientHeight) // 150-10*2 = 130;console.log(father.scrollHeight) // 150-10*2 = 130;console.log(father.offsetHeight) // 150</script>

(2)有垂直滚动条的情况下:

​<style>* {margin: 0;}#father {box-sizing: border-box;width: 150px;height: 150px;padding: 20px;border: 10px solid green;background: red;overflow: auto;}#son {width: 50px;height: 200px;background: blue; line-height: 50px;text-align: center;}</style><body><div id="father"><div id="son">son</div></div></body><script>var father = document.getElementById("father");// scrollHeight =内容高 + paddingTop + paddingBottomconsole.log(father.scrollHeight) // 200+20*2 = 240console.log(father.clientHeight) // 150-10*2 = 130console.log(father.offsetHeight) // 150</script>

Element.scrollTop - Web APIs | MDN

Element.scrollTop属性可以获取或设置一个元素的内容垂直滚动的像素数。

scrollTop可以被设置为任何整数值,同时注意:

如果一个元素不能被滚动(例如,它没有溢出,或者这个元素有一个"non-scrollable"属性),scrollTop将被设置为0。设置scrollTop的值小于0,scrollTop被设为0。如果设置了超出这个容器可滚动的值,scrollTop会被设为最大值。

《scrollLeft同理》

应用示例:

JS在线编辑器,JS在线运行,在线演示,调试测试代码

<style>* {margin: 0;}#father {width: 150px;height: 150px;background: red;overflow: auto;}#son {width: 50px;height: 200px;background: blue; line-height: 200px;text-align: center;}</style><body><div id="father"><div id="son">son</div></div></body><script>var father = document.getElementById("father");father.scrollTop = 150; // 如果设置了超出这个容器可滚动的值, scrollTop 会被设为最大值。console.log(father.scrollTop) // 50</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。