常规 onner 使用

我们都知道,img标签支持onerror事件,在装载文档或图像的过程中如果发生了错误,就会触发onerror事件。可以使用一张提示错误的图片代替显示不了的图片。

<img src="images/img.png" οnerrοr="notimgfound();"/>
<script type="text/javascript">
function notimgfound(obj) {

        obj.onerror = "";

        obj.src = "images/logoimgerror.png";

        obj.onerror = null; //解绑onerror事件

}

两个参数的实例:

<img src="images/img.png" οnerrοr="houseimgerror(this,1);"/>

<img src="images/img.png" οnerrοr="houseimgerror(this);"/>

function houseimgerror(obj,num3d) {
    obj.onerror = "";
    if(num3d == 1){
        obj.src = baseUrl+"/pc/common/images/list404_3d.jpg";
    }else{
        obj.src = baseUrl+"/pc/common/images/houseList404.jpg";
    }
    obj.οnerrοr=null;
    obj.jqimg = '';
}

</script>

通过vue绑定onerror实现:


<img :src="images/logo.png" :οnerrοr="defaultImg">

<script>

export default {

         name: "imgError",

         data() {

                   return {

                              defaultImg: 'this.src="' + require('images/logoError.png') + '"' //默认图地址

                    }

         }

}

</script>

 

通过vue自定义指令

 

//全局注册自定义指令,用于判断当前图片是否能够加载成功,可以加载成功则赋值为img的src属性,否则使用默认图片
Vue.directive('real-img', async function (el, binding) {//指令名称为:real-img
    let imgURL = binding.value;//获取图片地址
    if (imgURL) {
        let exist = await imageIsExist(imgURL);
        if (exist) {
            el.setAttribute('src', imgURL);
        } 
    }
})

/**
 * 检测图片是否存在
 * @param url
 */
let imageIsExist = function(url) {
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function () {
            if (this.complete == true){
                resolve(true);
                img = null;
            }
        }
        img.onerror = function () {
            resolve(false);
            img = null;
        }
        img.src = url;
    })
}

然后使用的时候就特别方便了,因为是全局注册的,所以每个页面都可以直接使用

<!--v-real-img 就是刚刚定义的指令,绑定的为真实要显示的图片地址。src为默认图片地址-->
<img src="images/logoError.png" v-real-img="images/logo.png">

 

Logo

前往低代码交流专区

更多推荐