简单代码:
$(document).ready(function(){
console.log($('.slide-background').width());
});
Run Code Online (Sandbox Code Playgroud)
和简单的HTML:
<div class="testdiv">
<img class="slide-background" src="img/slide.png"/>
</div>
Run Code Online (Sandbox Code Playgroud)
以及简单的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;
}
Run Code Online (Sandbox Code Playgroud)
为什么它会随时输出宽度?有时宽度实际上会被记录,但大多数时候返回0.
在jQuery $(document).ready()运行代码时,加载DOM(不包括图像),$(window).load()在加载所有内容时运行代码.
简单地说,图像宽度为0,因为它没有在代码运行时加载.
请$(window).load()改用.
DOM已准备就绪,但您的图像仍由浏览器呈现.
var $image = $('.testdiv img');
var img = new Image(); // in memory image
img.src = $image[0].src; // set SRC
img.onload = function(){ // as soon it's loaded
alert( img.width ) ; // WORKS!
}
Run Code Online (Sandbox Code Playgroud)