各种情况上JS获取元素宽高

各种情况下JS获取元素宽高

  为了叙述简单,这里仅拿width示例。

  情景一,元素style属性设置了width/height

  <div style="width:996px">test<div>
<script>
  var div = document.getElementsByTagName('div')[0];
  alert(div.style.width);
</script>默认分类

  如上,使用el.style.width即可。

  

如果没有在style属性中设置width,那么使用el.style.width将获取不到,如下

  <div>test<div>
<script>
  var div = document.getElementsByTagName('div')[0];
  alert(div.style.width);
</script>

  所有浏览器中弹出的是空字符串。即使将样式嵌在页面的css中也仍然获取不到,如下

  <style>
  div { 100px}
</style>


<div>test<div>
<script>
  var div = document.getElementsByTagName('div')[0];
  alert(div.style.width);
</script>

  这时候getComputedStyle或currentStyle将会派上用场。

  情景二,元素通过引入样式表设置width/height

  有两种方式引入样式表,一是使用link标签引入单独的css文件,二是直接在html页面中使用style标签。这里使用第二种方式测试。如下

  <style>
  div { 100px}
</style>
<div>test<div>
<script>
  function getStyle(el, name) {
    if(window.getComputedStyle) {
      return window.getComputedStyle(el, null);
    }else{
      return el.currentStyle;
    }
  }
  var div = document.getElementsByTagName('div')[0];
  alert(getStyle(div, 'width'));
</script>

  所有浏览器中均弹出了100px。说明通过getComputedStyle和currentStyle可以获取到元素被定义在样式表中的宽高。

  那如果元素即没有在style属性中设置宽高,也没有在样式表中设置宽高,还能用getComputedStyle或currentStyle获取吗?答案是getComputedStyle可以,currentStyle不可以 。如下

  <div>test<div>
<script>
  function getStyle(el, name) {
    if(window.getComputedStyle) {
      return window.getComputedStyle(el, null);
    }else{
      return el.currentStyle;
    }
  }
  var div = document.getElementsByTagName('div')[0];
  alert(getStyle(div, 'width'));
</script>

  div 既没有设置style属性,也没有引入样式表。在Firefox/IE9/Safari/Chrome/Opera中可以获取到宽高(浏览器默认),但IE6/7/8中却不行,返回的是auto。

注意,这里getStyle方法优先使用getComputedStyle,而IE9已经支持该方法。因此IE9中可以获取到宽高。但IE6/7/8不支持,只能使用currentStyle获取。

原文地址:https://www.cnblogs.com/huashao/p/6196592.html