【JavaScript相关】区分什么是“客户区坐标”、“页面坐标”、“屏幕坐标”(约169字)

区分什么是“客户区坐标”、“页面坐标”、“屏幕坐标”

  • 客户区坐标:鼠标指针在可视区中的水平坐标(clientX)和垂直坐标(clientY)
  • 页面坐标:鼠标指针在页面布局中的水平坐标(pageX)和垂直坐标(pageY)
  • 屏幕坐标:设备物理屏幕的水平坐标(screenX)和垂直坐标(screenY)
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body {
          margin: 0;
          height: 2000px;
        }
        #box {
          width: 200px;
          height: 200px;
          background-color: red;
          position: absolute;
          left: 100px;
          top: 100px;
        }
      </style>
    </head>
    <body>
      <div id="box"></div>
    
      <script>
        document.addEventListener('mousemove', function(event) {
          console.log('客户区坐标:', event.clientX, event.clientY);
          console.log('页面坐标:', event.pageX, event.pageY);
          console.log('屏幕坐标:', event.screenX, event.screenY);
        });
      </script>
    </body>
    </html>

如何获得一个DOM元素的绝对位置?

  • elem.offsetLeft:返回元素相对于其定位父级左侧的距离
  • elem.offsetTop:返回元素相对于其定位父级顶部的距离
  • elem.getBoundingClientRect():返回一个DOMRect对象,包含一组描述边框的只读属性,单位像素
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body {
          margin: 0;
          padding: 0;
        }
        #container {
          width: 500px;
          height: 500px;
          position: relative;
          border: 1px solid black;
        }
        #box {
          width: 100px;
          height: 100px;
          background-color: red;
          position: absolute;
          left: 200px;
          top: 200px;
        }
      </style>
    </head>
    <body>
      <div id="container">
        <div id="box"></div>
      </div>
    
      <script>
        var box = document.getElementById('box');
        
        var offsetLeft = box.offsetLeft;
        var offsetTop = box.offsetTop;
        console.log('offsetLeft:', offsetLeft);
        console.log('offsetTop:', offsetTop);
        
        var rect = box.getBoundingClientRect();
        console.log('rect:', rect);
        console.log('left:', rect.left);
        console.log('top:', rect.top);
      </script>
    </body>
    </html>

THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容