JS html元素以及偏移量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boonyaxnn/article/details/89086021
一、html元素

var html = document.documentElement;

1、获取视口的宽高

console.log('width',html.clientWidth);
console.log('height',html.clientHeight);

2、获取包含滚动条视口宽高  滚动条的宽度是17px

console.log('包含滚动条width',window.innerWidth);
console.log('包含滚动条Height',window.innerHeight);
var box = document.querySelector('.box');

3、offsetWidth/offsetHeight:当前元素的宽高+padding+border

console.log('box-height',box.offsetHeight);
console.log('box-width',box.offsetWidth);

4、clientWidth/clientHeight:当前元素的宽高+padding

console.log('box-height',box.clientHeight);
console.log('box-width',box.clientWidth);

二、偏移量

1. offsetParent
  描述:获取距离自己最近的已经定位的父元素
  语法:node.offsetParent
  注意:不要只观察结构 一定要查看是否定位
  例子:
    var a1 = document.querySelector('.a1');
    console.log(a1.offsetParent);
2. offsetLeft:
  描述:获取当前元素边框外到已经定位父元素边框内的水平距离
        当前元素外边距 + 已经定位父元素内边距
  语法:node.offsetLeft
  例子:
    var box = document.querySelector('.box');
    console.log('box',box.offsetLeft);
    var div1 = document.querySelector('.div1');
    console.log('div1',div1.offsetLeft);
    console.log(div1.offsetParent);
3.offsetTop:
  描述:获取当前元素边框外到已经定位父元素边框内的垂直距离
        当前元素外边距 + 已经定位父元素内边距
  语法:node.offsetTop
  例子:
    var box = document.querySelector('.box');
    console.log('box',box.offsetTop);
    var div1 = document.querySelector('.div1');
    console.log('div1',div1.offsetTop);
    console.log(div1.offsetParent);

猜你喜欢

转载自blog.csdn.net/boonyaxnn/article/details/89086021