JQuery.width () sometimes works; sometimes not?
Simple code:
$(document).ready(function(){
console.log($('.slide-background').width());
});
and simple html:
<div class="testdiv">
<img class="slide-background" src="img/slide.png"/>
</div>
Like plain CSS:
body {
margin: 0; padding: 0;
height: 100%; width: 100%;
}
html {
margin: 0; padding: 0;
height: 100%; width: 100%;
}
.testdiv {
overflow: hidden;
width: 100%;
height: 100%;
background-color: black;
}
Why does it output the width when it wants? Sometimes the width is actually recorded, however most of the time 0 is returned.
+3
source to share
3 answers
As the width is unknown until the image is loaded.
As the W3C recommends, you must set the width
and attributes height
for the <img>
correct width and height to be shown (and known) before the image finishes loading. If you have a very large image, your layout can be completely confusing so that it doesn't take up space before it loads.
+3
source to share