当前位置: 移动技术网 > IT编程>网页制作>CSS > DOM盒模型和位置 client offset scroll 和滚动的关系

DOM盒模型和位置 client offset scroll 和滚动的关系

2020年01月09日  | 移动技术网IT编程  | 我要评论

dom盒模型和位置 client offset scroll 和滚动的关系

概览

在dom里面有几个描述盒子位置信息的值,

  • 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 + border

.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;
  }
}

此种结构特点
如果垂直滚动条已经出来了

  • .container1 的上下 padding 区域也会有内容

向上滑动

  • 向上滑动, 实质是 .container2 向上滑动了
  • 因为.container2.position == relative  li.offsetparent  也是.container2 , 所以.container1.scrolltopli.offsettop 基准线都是.container2的上边框, 具有可比性

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网