js特效:鼠标滑过图片时切换为动图

效果展示

图片描述

事前准备

一张普通的静态图+与其对应的gif图。

实现思路

获取图片的src,改变其后缀,使其变成与之对应的gif图片。(很简单有木有= =)

具体实现

编写html代码

 <div class="section_02_icon icon_01">
                    <img src="img/icon01.png"  alt="" onerror="this.src='img/icon01.png'">
                    <p>最强大脑</p>
            </div>
            <div class="section_02_icon icon_02">
                <!-- onerror 如果替换的图片不存在 则用静态图 -->
                  <img src="img/icon02.png" alt="" onerror="this.src='img/icon02.png'">
                  <p>大开眼界</p>
            </div>
            <div class="section_02_icon icon_03">
                  <img src="img/icon03.png" alt="" onerror="this.src='img/icon03.png'">
                    <p>智能帮手</p>
            </div>
            <div class="section_02_icon icon_04">
                  <img src="img/icon04.png" alt="" onerror="this.src='img/icon04.png'">
                    <p>安全卫士</p>
            </div>

编写js代码

//改变图片src,用gif动图替换。
var suffix = "";
function imgSwitch(img,on){
    var src_png = img.children('img')[0].src; //获取图片src
    if(on){   //判断isHover 如果是hover,则获得图片后缀,不是则反之
      suffix=src_png.substring(src_png.lastIndexOf(".")+1,src_png.length); //得到后缀
    }
    var src1 = src_png.indexOf("/img"); 
    var src2 = src_png.substring(src1+1); //因为.src方法获取的是相对路径 ,这一步将其转换为绝对路径
    path=on?src2.replace('.'+suffix,'.gif'):src2.replace('.gif','.'+suffix); //将后缀改为gif or 将gif改为原来的后缀 取决于on的值
    img.find("img").attr('src',path);  //执行替换
}

 $(".section_02_icon").hover(function(){
           imgSwitch($(this),1);
    },function(){
           imgSwitch($(this),0);
    });

代码下载 链接:https://pan.baidu.com/s/1sneEbwx 密码:u8pg
我是新手,有不足的问题希望提出。

原文地址:https://www.cnblogs.com/twodog/p/12137505.html