42.获取元素宽高方式

获取元素宽高方式

通过getComputedStyle获取宽高

  • 获取的宽高不包括 边框和内边距
  • 即可以获取行内设置的宽高也可以获取CSS设置的宽高
  • 只支持获取, 不支持设置
  • 只支持IE9及以上浏览器
1
2
3
4
5
6
7
8
var oDiv = document.getElementById("box");
// oDiv.style.width = "166px";
// oDiv.style.height = "166px";
var style = getComputedStyle(oDiv);
// style.width = "166px";
// style.height = "166px";
console.log(style.width);
console.log(style.height);

通过currentStyle属性获取宽高

  • 获取的宽高不包括 边框和内边距

  • 即可以获取行内设置的宽高也可以获取CSS设置的宽高

  • 只支持获取, 不支持设置

  • 只支持IE9以下浏览器

1
2
3
4
5
6
7
8
9
var oDiv = document.getElementById("box");
// oDiv.style.width = "166px";
// oDiv.style.height = "166px";
var style = oDiv.currentStyle;
style.width = "166px";
style.height = "166px";
// console.log(style);
console.log(style.width);
console.log(style.height);

通过style属性获取宽高

  • 获取的宽高不包括 边框和内边距

  • 只能获取内设置的宽高, 不能获取CSS设置的宽高

  • 可以获取也可以设置

  • 高级低级浏览器都支持

    1
    2
    3
    4
    5
    var oDiv = document.getElementById("box");
    oDiv.style.width = "166px";
    oDiv.style.height = "166px";
    console.log(oDiv.style.width);
    console.log(oDiv.style.height);

以上获取的宽高不包括边框 , 内边距

offsetWidth和offsetHeight

  • 获取的宽高包含 边框 + 内边距 + 元素宽高
  • 即可以获取行内设置的宽高也可以获取CSS设置的宽高
  • 只支持获取, 不支持设置
  • 高级低级浏览器都支持
1
2
3
4
5
6
7
var oDiv = document.getElementById("box");
// oDiv.offsetWidth = "166px";
// oDiv.offsetHeight = "166px";
oDiv.style.width = "166px";
oDiv.style.height = "166px";
console.log(oDiv.offsetWidth);
console.log(oDiv.offsetHeight);

区别

  1. getComputedStyle/currentStyle/style
    获取的宽高不包括 边框和内边距
  2. offsetWidth/offsetHeight
    获取的宽高包括 边框和内边距
  3. getComputedStyle/currentStyle/offsetXXX
    只支持获取, 不支持设置
  4. style可以获取, 也可以设置
  5. getComputedStyle/currentStyle/offsetXXX
    即可以获取行内,也可以获取外链和内联样式
  6. style只能获取行内样式