完成加载后获取div的宽度和高度

时间:2015-12-25 03:55:51

标签: javascript html

我尝试使用javascript完成加载后获取div的宽度和高度,但是在图像完成加载之前它会获得div的宽度和高度。我该怎么做才能解决这个问题?



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

结果:

634:2

预期结果:

634:(More Than 2 Pixels)

2 个答案:

答案 0 :(得分:1)

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

listOfFiles.OrderBy(x => x.Tag.AlbumArtists[0]) // access the first item only.
             .ThenBy(x => x.Tag.Album);

答案 1 :(得分:0)

这是一个javascript代码段

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

&#13;
&#13;
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);
&#13;
#image {
border: 1px solid red;
width: 50%;
}
&#13;
<div id = 'image'>
<img id="actual_image" src = 'http://exmoorpet.com/wp-content/uploads/2012/08/cat.png'>
</div>
&#13;
&#13;
&#13;