在chrome问题中使用jquery的图像高度

Pra*_*sad 12 jquery height google-chrome image

$('img').height()0以chrome 返回,但它返回IE和firefox中的实际高度.

什么是实际的方法来获得铬的图像的高度?

JGa*_*ido 9

正如Josh所提到的,如果图像尚未完全加载,jQuery将不知道尺寸是什么.尝试这样的事情,以确保您只是在图像完全加载后才尝试访问它的尺寸:

var img = new Image();

$(img).load( function() {
    //-- you can determine the height before adding to the DOM
    alert("height: " + img.height);
    //-- or you can add it first...
    $('body').append(img);
    //-- and then check
    alert($('body img').height());
}).error( function() {
    //-- this will fire if the URL is invalid, or some other loading error occurs
    alert("DANGER!... DANGER!...");
});

$(img).attr('src', "http://sstatic.net/so/img/logo.png");
Run Code Online (Sandbox Code Playgroud)


Jos*_*hua 1

我的假设是在图像加载完成之前调用该函数。您能否尝试延迟该函数以查看是否确实如此?如果是这种情况,您可以在运行该函数之前使用计时器来作弊。

检测图像何时加载有点复杂。查看此脚本以获取一些想法- 也许它对您有用。

  • @Frank,当 DOM 创建完成时,主体 onload 会被调用,但不能保证 DOM 中的资源将完成加载(包括图像)。 (2认同)