【问题标题】:Chaging Src of Image Not Working On First Load更改图像的 Src 在首次加载时不起作用
【发布时间】: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


【解决方案1】:

$(document).ready() 在页面的生命周期中运行得太快。如果图像仍在从服务器下载,则您将没有尺寸。尝试改用$(window).load()

https://stackoverflow.com/a/8396457/120955

【讨论】:

    猜你喜欢
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多