解决js图片加载时出现404的问题

运营网站久了之后,无法避免会出现图片404的情况,原因可能是图片文件本来就不存在或目前不存在。常见的解决方案是将404图片 隐藏或者是替换为默认的图片 。 
img标签事件属性
img标签可使用的时间属性有:
onabort, onbeforeunload, onblur, onchange, onclick, oncontextmenu, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, onerror, onfocus, onkeydown, onkeypress, onkeyup, onload, onmessage, onmousedown, onmousemove, onmouseover, onmouseout, onmouseup, onmousewheel, onresize, onscroll, onselect, onsubmit, onunload
img标签常用的事件如下:

onerror: 图像加载过程中发生错误时被触发。
onabort: 图片加载的时候,用户通过点击停止加载时触发,通常在这里触发一个提示:“图片正在加载”。
onload: 当图片加载完成之后触发。

1. 对图片监听onerror事件

<img src= "someimage.png" onerror= "imgError(this);" />
  
// 原生JS:
function imgError(image){
  // 隐藏图片
  image.style.display = 'none' ;
  // 替换为默认图片
  // document.getElementById("img").setAttribute("src", "images/demo.png");
}
  
// 使用jQuery处理:
function imgError(image){
  $(image).hide();
  // $(this).attr("src", "images/demo.png");
}

注意:需要将处理函数定义在head,防止图片加载出错时没有读取到处理函数

2. 使用jQuery监听error

// 通常不会再HTML里面内联js,可以使用.error对图片进行监听处理
$( '#test img' ).error( function () {
  $( this ).hide();
  // $(this).attr("src", "images/demo.png");
});
注意: jQuery加载需要在img前,处理函数需在img后

3. 使用函数处理

// 原生JS解决方案
function $id(id) {
  return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o, t) {
  return ( typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;
}
  
// 主要逻辑
function image(src, cfg) {
  var img, prop, target;
  cfg = cfg || (isType(src, 'o' ) ? src : {});
  
  img = $id(src);
  if (img) {
   src = cfg.src || img.src;
  } else {
   img = document.createElement( 'img' );
   src = src || cfg.src;
  }
  
  if (!src) {
   return null ;
  }
  
  prop = isType(img.naturalWidth, 'u' ) ? 'width' : 'naturalWidth' ;
  img.alt = cfg.alt || img.alt;
  
  // Add the image and insert if requested (must be on DOM to load or
  // pull from cache)
  img.src = src;
  
  target = $id(cfg.target);
  if (target) {
   target.insertBefore(img, $id(cfg.insertBefore) || null );
  }
  
  // Loaded?
  if (img.complete) {
   if (img[prop]) {
    if (isType(cfg.success, 'f' )) {
     cfg.success.call(img);
    }
   } else {
    if (isType(cfg.failure, 'f' )) {
     cfg.failure.call(img);
    }
   }
  } else {
   if (isType(cfg.success, 'f' )) {
    img.onload = cfg.success;
   }
   if (isType(cfg.failure, 'f' )) {
    img.onerror = cfg.failure;
   }
  }
  
  return img;
}
 以上函数有许多用处:
1. 获取图片信息:图片是否可下载,图片宽高
image( 'img' ,{
  success : function () { alert( this .width + "-" + this .height); },
  failure : function () { alert( 'image 404!' ); },
});
  
// 验证资源是否下载
image( 'images/banner/banner_2.jpg' , {
  success : function () {console.log( 'sucess' )},
  failure : function () {console.log( 'failure' )},
  target : 'myContainerId' ,
  insertBefore : 'someChildOfmyContainerId'
})
  2. 下载并插入图片
var report = $id( 'report' ),
  callback = {
   success : function () {
    report.innerHTML += '<p>Success - ' + this .src + ' (' + this .offsetWidth+ 'x' + this .offsetHeight+ ')</p>' ;
   },
   failure : function () {
    report.innerHTML += '<p>Failure - ' + this .src + ' (' + this .offsetWidth+ 'x' + this .offsetHeight+ ')</p>' ;
   },
   target : 'target'
  };
  
image( 'img' , callback);
image( 'images/banner/banner_2.jpg' , callback);
以上就是js针对图片加载时出现404问题的解决办法,希望大家有所收获。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值