【问题标题】:Getting the width and height of a div after it finished loading加载完成后获取div的宽度和高度
【发布时间】:2015-12-25 03:55:51
【问题描述】:

我试图在使用 javascript 完成加载后获取 div 的宽度和高度,但它在图像完成加载之前获取 div 的宽度和高度。我能做些什么来解决这个问题?

<script type = "text/javascript">
var width = document.getElementById("image").offsetWidth;
var height = document.getElementById("image").offsetHeight;
alert(width+":"+height);
</script>
#image {
border: 1px solid red;
width: 50%;
}
<div id = 'image'>
<img src = 'http://exmoorpet.com/wp-content/uploads/2012/08/cat.png'>
</div>

结果:

634:2

预期结果:

634:(More Than 2 Pixels)

【问题讨论】:

标签: javascript html


【解决方案1】:

使用 .load 等待该元素加载到 dom 中

$("#image").load(function() {
  var width = document.getElementById("image").offsetWidth;
  var height = document.getElementById("image").offsetHeight;
  alert(width+":"+height);
});

【讨论】:

    【解决方案2】:

    这是一个javascript sn-p

    注意:您的宽度为 50%,因此取决于窗口的大小,您的 div 宽度会发生变化。因此,除非您使用绝对测量单位,否则您不会获得固定宽度

    var width=height=null;
    function handler(){
    width=document.getElementById('image').offsetWidth;
    height=document.getElementById('image').offsetHeight;
    alert('width:'+width+',height: '+height);
    }
    document.getElementById('actual_image').addEventListener('load',handler,false);
    #image {
    border: 1px solid red;
    width: 50%;
    }
    <div id = 'image'>
    <img id="actual_image" src = 'http://exmoorpet.com/wp-content/uploads/2012/08/cat.png'>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 2013-05-04
      • 2012-06-15
      • 1970-01-01
      • 2013-08-15
      • 2018-10-13
      相关资源
      最近更新 更多