当前位置:网站首页>关于元素位置和尺寸

关于元素位置和尺寸

2022-06-11 17:26:00 大船叔叔

元素位置的判断

浏览器,html元素 屏幕都有坐标系,原点是左上角 x轴往右 y轴往下
目标元素指的是 : 触发事件的元素

  • 1.求点击的位置在目标元素上的元素
  • (e.offsetX,e.offsetY)
  • 2.求点击位置在浏览器上的坐标
  • (e.clientX,e.clientY)
  • 3.求点击位置到屏幕上的坐标 基本不用
  • (e.screenX,e.screenY)
      
          // 可以用来判断边框的大小
          // 相对于元素自身边框的距离 如果没有边框 结果为0 也就是边框多大 他多大
         div.clientLeft
         div.clientTop

     
        // 相对于非静态定位的父元素左上角的位置距离 
        //(1).如果父辈元素中有定位的元素,那么就返回距离当前元素最近的定位元素边缘的距离。
        //(2).如果父辈元素中没有定位元素,那么就返回相对于body左边缘距离。
        // 注意:offsetLeft 和 offsetTop 只能取值 不能赋值
        // 如果要修改元素的位置 使用定位方式
      
         div.offsetLeft
         div.offsetTop

        // div3.offsetLeft = 100; 不可以通过赋值进行修改
        // 使用定位个margin可以修改 border和padding不可以修改 
        div3.style.position = 'absolute';
        div3.style.left = '100px';
        console.log('div3:' + div3.offsetLeft); 
        console.log('div3:'+ div3.offsetTop);

元素尺寸

  // 1.显示器屏幕的尺寸
        console.log(screen.width);
        console.log(screen.height);

        // 2.网页的尺寸 当前网页的可视区域大小(可能随着页面大小而改变)
        console.log(document.documentElement.clientHeight);
        console.log(document.documentElement.clientWidth);
        // 同上
        console.log(window.innerHeight);
        console.log(window.innerWidth);

        // html标签的大小
        console.log(document.documentElement.offsetHeight);
        console.log(document.documentElement.offsetWidth);
        // 标签尺寸
        var div = document.getElementById('divID');
        // 查看元素width height
        console.log(div.style.width);
        console.log(div.style.height);
        // 修改元素宽高
        div.style.height = '200px';
        div.style.width = '200px';


        // 无法获取到width和height
        var div1 = document.getElementById('divID1');
         // 查看元素width height
        console.log(div1.style.width);
        console.log(div1.style.height);
        // 总结 div.style.width 和 div.style.height 只能获取行内样式和js设置的width和height属性
        // 不能获得内部样式css中写的width和height

        // 内尺寸 不包含边框 包含padding + height和width
        div1.clientHeight
        div1.clientWidth

        // 外尺寸 包含边框和padding +height和width
        div1.offsetHeight
        div1.offsetWidth

原网站

版权声明
本文为[大船叔叔]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_48785803/article/details/125170345