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

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

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

正如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"); 

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

检测图像何时加载有点复杂。 看一下这个脚本的一些想法 – 也许它会对你有用。

预加载图像和设置回调函数可能是您正在寻找的:

 // 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); }); }); 

我使用的一个稍微丑陋但有效的修复是使用后端语言,在我的情况下,php,在将图像发送到浏览器之前获取高度并将其设置在图像上。

它很难看,但简单快捷

尝试使用图像预加载器, 这是我写的另一个问题的答案。

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

 $(this).height(); 

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

 this.height; 

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

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