david2tdw / blog

学习记录
1 stars 1 forks source link

[HTML] Element.getBoundingClientRect() #117

Open david2tdw opened 4 years ago

david2tdw commented 4 years ago

例子:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        /* 如果不加margin: 0, left会有8px的额外空间 */
        padding: 0;
        margin: 0;
      }
      .box {
        width: 2000px;
        height: 300px;
        margin-left: 100px;
        margin-top: 30px;
        background: green;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <div class="box" id="demo">
      点击矩形,输出位置。
      <pre>
      .box {
        width: 2000px;
        height: 300px;
        margin-left: 100px;
        margin-top: 30px;
        background: green;
      }
      </pre>
    </div>
    <script>
      document.getElementById('demo').onclick = function() {
        if (document.documentElement.getBoundingClientRect) {
          console.log('left:' + this.getBoundingClientRect().left)
          console.log('top:' + this.getBoundingClientRect().top)
          console.log('right:' + this.getBoundingClientRect().right)
          console.log('bottom:' + this.getBoundingClientRect().bottom)
          console.log('width:' + this.getBoundingClientRect().width)
          console.log('height' + this.getBoundingClientRect().height)

          console.log('scrollLeft:' + document.documentElement.scrollLeft)
          console.log('scrollTop:' + document.documentElement.scrollTop)
          var X = this.getBoundingClientRect().left + document.documentElement.scrollLeft
          var Y = this.getBoundingClientRect().top + document.documentElement.scrollTop
          console.log('Demo的位置是X:' + X + ';Y:' + Y)
        }
      }
    </script>
  </body>
</html>

document.documentElement.scrollLeft: 横滚动条距离屏幕左边距的距离。 document.documentElement.scrollTop: 纵滚动条距离屏幕顶部的距离。

body 的默认样式(chrome):

body {
    display: block;
    margin: 8px;
 }
david2tdw commented 4 years ago

element.getBoundingClientRect()返回一个Object对象,该对象有6个属性:top, left, bottom, right, width, height。

getClientRects() 和 getBoundingClientRect() 的用法和区别

david2tdw commented 4 years ago

image

david2tdw commented 4 years ago

top: 元素顶部距离窗口顶端的距离。 left: 元素左边距离窗口左边的距离。 bottom:元素底边距离窗口上边的距离。 right: 元素右边距离窗口左边的距离。