3

简单代码:

$(document).ready(function(){
    console.log($('.slide-background').width());
});

和简单的html:

<div class="testdiv">
      <img class="slide-background" src="img/slide.png"/>
</div>

以及简单的 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;
        }

为什么它会随时输出宽度?有时宽度实际上会被记录,但大多数时候会返回 0。

4

3 回答 3

7

在 jQuery$(document).ready()中,在加载 DOM(不包括图像)时$(window).load()运行代码,在加载所有内容时运行代码。

简而言之,图像宽度为 0,因为它在您的代码运行时尚未加载。

改为使用$(window).load()

于 2013-02-04T14:22:36.327 回答
5

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!
}
于 2013-02-04T14:21:33.283 回答
3

因为在图像加载之前宽度是未知的。

正如 W3C 建议的那样,您应该设置widthheight属性,<img>以便在图像完成加载之前显示(并且已知)正确的宽度和高度。如果您有一个非常大的图像,您的布局可能会因为它在加载之前不占用任何空间而完全搞砸。

于 2013-02-04T14:21:19.417 回答