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

来源:互联网 发布:英国女王大学 知乎 编辑:程序博客网 时间:2024/05/19 08:00

运营网站久了之后,无法避免会出现图片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事件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<img src="someimage.png"onerror="imgError(this);"/>
  
// 原生JS:
functionimgError(image){
 // 隐藏图片
 image.style.display = 'none';
 // 替换为默认图片
 // document.getElementById("img").setAttribute("src", "images/demo.png");
}
  
// 使用jQuery处理:
functionimgError(image){
 $(image).hide();
 // $(this).attr("src", "images/demo.png");
}

注意:需要将处理函数定义在head,防止图片加载出错时没有读取到处理函数
 2. 使用jQuery监听error

?
1
2
3
4
5
// 通常不会再HTML里面内联js,可以使用.error对图片进行监听处理
$('#test img').error(function() {
 $(this).hide();
 // $(this).attr("src", "images/demo.png");
});

注意:jQuery加载需要在img前,处理函数需在img后
3. 使用函数处理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 原生JS解决方案
function$id(id) {
 return!id || id.nodeType === 1 ? id : document.getElementById(id);
}
functionisType(o, t) {
 return(typeofo).indexOf(t.charAt(0).toLowerCase()) === 0;
}
  
// 主要逻辑
functionimage(src, cfg) {
 varimg, 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) {
  returnnull;
 }
  
 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;
  }
 }
  
 returnimg;
}

 以上函数有许多用处:
1. 获取图片信息:图片是否可下载,图片宽高

?
1
2
3
4
5
6
7
8
9
10
11
12
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. 下载并插入图片

?
1
2
3
4
5
6
7
8
9
10
11
12
13
varreport = $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 0
原创粉丝点击