博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用JavaScript为一张图片设置备选路径
阅读量:4690 次
发布时间:2019-06-09

本文共 1310 字,大约阅读时间需要 4 分钟。

在做网页开发的时候,有时候希望给图片设置一个备选路径,即,当src属性对应的主路径加载失败的时候,图片可以马上切换到备选路径。这样,即使主路径失效了,显示备用路径也不会影响网页的正常体验。

注意到网页中一张图片加载失败会触发error事件,因此可以使用DOM模型中的load和error事件实现这一效果。

src1='main/image.jpg' //主路径src2='another/image.jpg' //备用路径

jQuery 1.8以前

使用load和error方法捕捉事件

$('#imgMap' ).attr("src",src1).load(function(){console.log("图片加载成功")                }).error(function(){                    console.log("图片加载失败,切换路径")                    $('#imgMap').attr('src',src2)                        });

jQuery 1.8

由于jQuery1.8之后load()方法和error()方法已经废弃了,因此可以使用bind方法绑定事件

$('#img').attr("src",src1).bind( "load", function() {  console.log("图片加载成功")}).bind("error",function(){    console.log("图片加载失败,切换路径")            $('#img').attr('src',src2)   });

jQuery 3.0

jQuery3.0以后,统一使用on方法捕获事件

$('#img').attr("src",src1).on( "load", function() {  console.log("图片加载成功")}).on("error",function(){    console.log("图片加载失败,切换路径")            $('#img').attr('src',src2)   });

JavaScript

不想使用jQuery插件时,也可以调用JavaScript原生方法。使用addEventListener方法监听事件。

var Image = document.getElementById('img');Image.src=src1;Image.addEventListener('load', function(event) {             console.log("图片加载成功")});Image.addEventListener('error', function(event) {            console.log("图片加载失败,切换路径")             Image.src=src2;});

(完)

转载于:https://www.cnblogs.com/zhmhhu/p/6246540.html

你可能感兴趣的文章