• 使用JavaScript为一张图片设置备选路径


    在做网页开发的时候,有时候希望给图片设置一个备选路径,即,当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;
    });
    复制代码

    (完)

  • 相关阅读:
    zTree实现地市县三级级联封装类
    zTree实现地市县三级级联报错(二)
    zTree实现地市县三级级联报错(一)
    FusionCharts报错
    当分页语句遇到union all
    两表关联更新,用于update 回滚
    Invalid file system control data detected
    expect: spawn id exp4 not open
    目的可疑,但方法很值得学习的书——leo鉴书56
    下载jQuery EasyUI出现网络问题
  • 原文地址:https://www.cnblogs.com/libin-1/p/6246733.html
Copyright © 2020-2023  润新知