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 + paddingBottom
  console.log(father.scrollHeight) // 200+20*2 = 240
  console.log(father.clientHeight) // 150-10*2 = 130
  console.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> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值