JQuery check image exist

丶灬走出姿态 提交于 2019-12-13 09:35:27

问题


Hi i'm trying to display different image in different part of my site, but i need to display a default image if image doesn't exist.

here is my code: the problem is to check the img width but is alway

jQuery(document).ready(function () {

    var $pathname = window.location.pathname;
    $item = 'http://www.lotus-nascita.it/images/headers-hover/corsi-preparto.jpg';
    if ($pathname == '/') {
        $pathname = $pathname + 'home';
        $item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';

    }
    var img = new Image();
    img.onload = function () {}
    img.src = $item;
    if (img.height != 0) {

        $item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';
    }

    jQuery('#header').fadeOut('fast', function () {
        jQuery('#header').css({
            "background": 'url("' + $item + '")'
        });
        jQuery('#header').fadeIn('slow');

    });
});

回答1:


The height is always zero, as you have to wait for the image to load before it has a height ?

var item = 'http://www.lotus-nascita.it/images/headers-hover' + $pathname + '.jpg';
var img  = new Image();

img.onload = function () {
  if (this.height === 0) {
      item = 'http://www.lotus-nascita.it/images/headers-hover/corsi-preparto.jpg';
  }
}
img.src = item;



回答2:


I would try something like this in vanilla:

<img src="image.gif" onerror="this.src = 'default.gif'">

Or jQuery:

$(img).error(function() {
   $(this).attr("src","default.gif");
}).attr("src",$item);



回答3:


Try

var $myImg = $("<img>").attr("src", $item);
if($myImg.height != 0) { ... }


来源:https://stackoverflow.com/questions/16596206/jquery-check-image-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!