【发布时间】:2015-09-11 06:46:58
【问题描述】:
我已经编写了一些代码,可以在加载时检查图像的自然大小,如果它符合特定标准,则更改 src.src。该脚本运行良好,但由于某种原因,它在我第一次加载页面时无法运行。
如果我刷新页面,则会按预期替换图像。我猜这与 dom 中不可用的自然大小有关,但似乎无法在网上找到任何解决方案。
任何帮助将不胜感激。
谢谢
史蒂夫
这是我的代码...
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('img').each(function(index){
// check if browser is html5 compatible or not
var img = jQuery(this);
if (typeof img.naturalWidth == "undefined") {
var newImg = new Image();
newImg.src = img.attr('src');
if(newImg.height == 80 && newImg.width == 80){
jQuery(this).attr("src", "/2/files/no_image.jpg")
}
}else{
if(img.naturalWidth == 80 && img.naturalHeight == 80)jQuery(this).attr("src", "/2/files/no_image.jpg");
}
});
});
</script>
【问题讨论】:
-
在从源加载图像之前,您无法可靠地测试图像尺寸。您的图像大小测试应在图像对象的“加载”处理程序中完成。
-
我改为 window.load 而不是 document.ready,现在它工作正常。谢谢!
标签: javascript jquery