[英]jQuery image height/width in Chrome
我正在尝试获取图像的宽度/高度以设置父容器的宽度/高度。 这是我这样做的代码:
var current_img = temp.find(".test-img").attr('src', c['img']).addClass("active-image");
然后我通过
current_img.css('width');
我遇到的问题是 chrome 在图像之前加载 jscript,因此 function 返回 null。 所以我把这段代码放在一起:
$(".test-img").each(function (index) {
$(this).load(function() {
imgwidth = $(this).css('width');
imgheight = $(this).css('height');
if (imgwidth != "0px" && imgheight != "0px")
$(this).parent().addClass('center').css({'width' : imgwidth, 'height' : imgheight});
});
});
第一次加载页面时这似乎工作正常,但是当调用 function 时,它返回 null。 此外,当我在本地打开页面时,它似乎工作正常,但是当托管在我的网络服务器上时,我遇到了这个问题。
好的,经过大量研究,我找到了解决方案。 这并不完美,但迄今为止我想出的最好的。
var img = new Image(); //create new image
$(img).append("div").fadeIn('fast', function() { //We use the callback function from fadein
var width = $(img).width();
var height = $(img).width();
});
此解决方法依赖于 fadeIn 将仅在正确加载图像后执行 function。 我的问题是我正在清空包含图像的 div 并重新填充它,但它仍然缓存在浏览器中。 所以 img.load() 没有做任何事情,因为它检测到图像确实已加载。
可以停止对已经存在于浏览器缓存中的图像进行触发
希望这可以帮助!
使用$('img').css('width')
你得到图像样式的宽度属性值而不是实际图像的宽度,使用$('img').width()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.