一文徹底弄清楚元素的高度和距離屬性

元素的位置屬性一直是很容易弄混淆的地方,各種高度寬度距離,每次使用的時(shí)候都需要各種查查查。今天就將相關(guān)屬性做一個(gè)歸類(lèi)整理,通過(guò)畫(huà)圖以最直觀的方式展現(xiàn),也方便日后查閱。

client 相關(guān)屬性

  • clientWidth/clientHeight

    表示一個(gè)元素的可視區(qū)域的寬高,包含元素內(nèi)容以及內(nèi)邊距,不包含滾動(dòng)部分。


    client.png

offset 相關(guān)屬性

  • offsetWidth/offsetHeight

    表示一個(gè)元素的標(biāo)準(zhǔn)寬高,它包含了邊框、內(nèi)邊距、元素內(nèi)容以及滾動(dòng)條。


    offset.png
  • offsetLeft/offsetTop

    表示當(dāng)前元素頂部/左邊距離最近父元素頂部/左邊的距離。


    scrolltop.png

scroll 相關(guān)屬性

  • scrollWidth/scrollHeight

    表示一個(gè)元素內(nèi)容區(qū)域的實(shí)際大小,包括不在頁(yè)面中的可滾動(dòng)部分(內(nèi)容和內(nèi)邊距)。


    scroll.png
  • scrollTop/scrollBottom

    表示在有滾動(dòng)條的時(shí),元素可視區(qū)域頂部距離元素頂部的距離,也就是已經(jīng)滾動(dòng)了多少距離。


    scrolltop.png

拓展應(yīng)用 - 滾動(dòng)加載

示例:


scrollMore.png

代碼:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>滾動(dòng)加載</title>
    <style> .parent {
        width: 300px;
        height: 200px;
        margin: 100px auto;
        border: 1px solid #ccc;
        overflow-y: scroll;
        word-break: break-all;
      }</style>
  </head>
  <body>
    <div class="parent" id="target">
      <div class="child">
        gagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagds
      </div>
    </div>
    <script> let target = document.getElementById("target");
      target.addEventListener("scroll", function () {
        const clientHeight = target.clientHeight;
        const scrollTop = target.scrollTop;
        const scrollHeight = target.scrollHeight;
        if (clientHeight + scrollTop >= scrollHeight) {
          // 到底部了
          console.log("到底部了");
        }
      });</script>
  </body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容