javascript - 用 jquery 替换损坏的图像

标签 javascript php jquery

<分区>

我正在尝试替换未找到的图像,或者宽度或高度为 1 像素的图像。我设法用 PHP 做到了这一点:

$imgName = $resultList->IMAGE1; // ex http://www.domain.com/image.png
  if (@file_get_contents($imgName) && $imgName !== 'h') {
    // detects the image size (NOT based on width and height attributes)
$imgNamearray = getimagesize($imgName); 
$size = $imgNamearray[3];
    if ($size == 'width="1" height="1"') {
      $imgName = $base_path . 'uploads/no-img.jpg';
    }
  } else {
    $imgName = $base_path . 'uploads/no-img.jpg';
  }

我在 jQuery 中试过这段代码:

$('body').append('<div id="init"><img id="myimg" src="http://www.google.co.uk/intl/en_com/images/srpr/logo1w.png" /></div>');
$('#init').hide();

$('#myimg').bind("load",function(){
    alert(this.height)
})

可以在此处的 fiddle 中找到 http://jsfiddle.net/WMpSy/但我是 jQuery 的菜鸟,请帮助我。非常感谢。

最佳答案

如果您尝试通过 javascript 执行此操作而不更改您的 HTML,那么您可以这样做:

$(document).ready(function() {
    function checkImg(img) {
        if (img.naturalHeight <= 1 && img.naturalWidth <= 1) {
            // undersize image here
            img.src = "upload/no-img.jpeg";
        }
    }

    $("img").each(function() {
        // if image already loaded, we can check it's height now
        if (this.complete) {
            checkImg(this);
        } else {
            // if not loaded yet, then set load and error handlers
            $(this).load(function() {
                checkImg(this);
            }).error(function() {
                // img did not load correctly
                // set new .src here
                this.src = "upload/no-img.jpeg";
            });

        }
    });
});

如果您需要 IE8 的支持(没有 naturalHeight 和 naturalWidth),可以使用描述的解决方法 here .

关于javascript - 用 jquery 替换损坏的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23584446/

相关文章:

c# - 有没有一种直接的方法来检索浏览器呈现但未在实际 html 文件中硬编码的文本?

javascript - 使用水合物而不是从 react-dom 渲染时检测损坏的图像

php - 使用 php 在 Moodle 中创建类(class)

javascript - 对 JavaScript 多维数组中的元素进行排序

javascript - 根据 Controller 的结果处理 View 中的事物

JavaScript 函数调用。转义字符串中的引号

javascript - jQuery 滚动条问题

javascript - Jquery Unobtrusive 验证不适用于 View 模型列表中第一个之后的项目 - c# MVC 4

php - Yosemite 升级后 Apache 虚拟主机损坏

javascript - 使用 Javascript/jQuery 或 PHP 解析 HTML