DOM盒模型和位置 client offset scroll 和滾動的關係

DOM盒模型和位置 client offset scroll 和滾動的關係

概覽

在dom裏面有幾個描述盒子位置信息的值,css

  • pading border margin
  • width height
  • client
    • clientWidth 不要border
    • clientHeight 不要border
  • offset
    • offsetTop
    • offsetLeft
    • offsetWidth  要border
    • offsetHeight  要border
  • scroll
    • scrollTop
    • scrollHeight
    • scrollLeft
    • scrollWidth

盒模型

生產環境通常使用 box-sizing: border-box,
效果:
    width == content.width + pading + border
    height == content.height + pading + borderhtml

.antd-pro-pages-test-dom-index-box {
    box-sizing: border-box;
    width: 100px;
    height: 100px;
    padding: 5px;
    border-color: grey;
    border-style: solid;
    border-width: 5px;
    margin: 5px;
}

image.png

滾動

<div class="container1" style="overflow: auto; height: 200px; width: 200px">
  <ul class="container2" style="position: relative">
     <li>1</li>
     <li>1</li>
     <li>1</li>
     <li>1</li>
  </ul>
</div>
// 把item 放在container的可視區域範圍內
function scrollToDom(container, item){
  // 當前元素 上邊框上邊 到 基線 的距離
    const itemTop = item.offsetTop;
  // 當前元素 下邊框下邊 到 基線 的距離
  const itemBottom = itemTop + item.offsetHeight;
  
  // container 上邊框下邊 距離 基線距離
  const containerTop = container.scrollTop;
  // container 下邊框上邊 距離 基線距離
  const containerBottom = containerTop + container.clientHeight;
  
  if(itemTop < containerTop){
     container.scrollTop = itemTop;
   }
  
  if(itemBottom > containerBottom){
     container.scrollTop = itemBottom - container.clientHeight;
  }
}

此種結構特色
若是垂直滾動條已經出來了typescript

  • .container1 的上下 padding 區域也會有內容

向上滑動antd

  • 向上滑動, 實質是 .container2 向上滑動了
  • 由於.container2.position == relative  li.offsetParent  也是.container2 , 因此.container1.scrollTopli.offsetTop 基準線都是.container2的上邊框, 具備可比性
相關文章
相關標籤/搜索