JS之DOM篇offset偏移量

偏移量主要是指offsetLeft、offsetTop、offsetHeight、offsetWidth这四个属性。偏移参照的是定位父级offsetParent

定位父级

定位父级(offsetParent)值的是与当前元素最近的经过定位(position不等于static)的父级元素,主要分为下列几种情况

  1. 元素自身有fixed定位,那么offsetParent结果为null。因为fixed相对的是视口定位
  2. 元素自身无fixed定位,且父级元素都未经过定位,offsetParent的结果为<body><body>元素的offsetParent为null
  3. 元素自身无fixed定位,且父级元素存在经过定位的元素,offsetParent的结果为离自身元素最近的经过定位的父级元素

偏移量

偏移量共包括offsetHeight、offsetWidth、offsetLeft、offsetTop这四个属性

offsetHeight

offsetHeight表示元素在垂直方向上占用的空间大小,无单位(以像素px计)

offsetHeight = border-top-width + padding-top + height + padding-bottom + border-bottom-width

offsetWidth

offsetWidth表示元素在水平方向上占用的空间大小,无单位(以像素px计)

offsetWidth = border-left-width + padding-left + width + padding-right + border-right-width
<style>
  #test {
     100px;
    height: 100px;
    background: teal;
    border: 5px solid red;
    padding: 10px 20px;
    margin: 10px 20px;
  }
</style>
<div id="test"></div>
<script>
  console.log(test.offsetWidth) // 150
  console.log(test.offsetHeight) // 130
</script>

注意: 如果元素有垂直滚动条,offsetWidth包含滚动条的宽度;如果元素有水平滚动条,offsetHeight包含滚动条的高度

offsetTop

offsetTop表示元素的上外边框至offsetParent元素的上内边框之间的像素距离

offsetLeft

offsetLeft表示元素的左外边框至offsetParent元素的左内边框之间的像素距离

<style>
  #out {
    position: relative;
     200px;
    height: 200px;
    background: yellow;
    border: 5px solid green;
  }
  #test {
     100px;
    height: 100px;
    background: teal;
    border: 5px solid red;
    padding: 10px 20px;
    margin: 10px 20px;
  }
</style>
<div id="out">
  <div id="test"></div>
</div>
<script>
  console.log(test.offsetTop) // 10
  console.log(test.offsetLeft) // 20
</script>

页面偏移

要获取元素在页面上的偏移量,可以把该元素的offsetLeft和offsetTop与其offsetParent元素的offsetLeft和offsetTop相加,一直循环到根元素,就可以获取元素在页面上的偏移量

function offset (el) {
  let top = el.offsetTop
  let left = el.offsetLeft
  while (el.offsetParent) {
    el = el.offsetParent
    top += el.offsetTop
    left += el.offsetLeft
  }
  return {
    left: left,
    top: top
  }
}
<style>
  body {
    padding: 0;
    margin: 0;
  }
  #test {
     100px;
    height: 100px;
    background: teal;
    border: 5px solid red;
    padding: 10px 20px;
    margin: 10px 20px;
  }
</style>
<div id="test"></div>
<script>
  function offset (el) {
  let top = el.offsetTop
  let left = el.offsetLeft
  while (el.offsetParent) {
    el = el.offsetParent
    top += el.offsetTop
    left += el.offsetLeft
  }
  return {
    top: top,
    left: left
  }
}

console.log(offset(test)); // {top: 10, left: 20}
</script>

注意事项

  1. 偏移量属性是只读的
  2. 设置了display:none;的元素,偏移量属性值为0
  3. 每次访问偏移量属性都会重新计算。出于性能考虑,对于需要重复计算偏移量的元素,可以把值保存到变量中
优秀文章首发于聚享小站,欢迎关注!
原文地址:https://www.cnblogs.com/yesyes/p/15352421.html