在dom裏面有幾個描述盒子位置信息的值,css
生產環境通常使用 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; }
<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
向上滑動了li.offsetParent
也是.container2
, 因此.container1.scrollTop
和 li.offsetTop
基準線都是.container2
的上邊框, 具備可比性