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

时间:2009-11-16 18:10:21

标签: jquery image google-chrome height

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

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

7 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

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

检测图像何时加载有点复杂。 Have a look at this script for some ideas - 也许这对你有用。

答案 2 :(得分:1)

我使用的一个稍微丑陋但有效的修复方法是使用后端语言(在我的案例中为php)获取高度并在将其发送到浏览器之前将其设置在图像上。

它很难看,但简单快捷

答案 3 :(得分:1)

预加载图像并设置回调函数可能正是您所需要的:

// simple image preloader
function getHeight(el,fn) {
    var img = new Image();
    img.onload = function() { fn(img.height); };
    img.src = el.attr("src");
}

$("img").each(function(){
    getHeight($(this),function(h){
        // what you need to do with the height value here
        alert(h);
    });
});

答案 4 :(得分:0)

尝试使用图像预加载器here's one我写了another question的答案。

答案 5 :(得分:0)

刚刚做了一些实验,我发现了

$(this).height();

返回0 - 但是如果你只使用普通的旧JS

this.height;

我得到了正确的图像高度。

答案 6 :(得分:-1)

遇到同样的问题:事先通过CSS或HTML设置宽度和高度。