在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
的上边框, 具备可比性