如果你想实现 hover 的的效果,
如果每张图片都会触发替换src,则在 img 标签中,再加一个attr,data-src,data-src 存放你需要替换的图片路径。
你的html应当这样子写:
更新: 由于你需要一个简单地动画,所以我就给你做了一个动画。javascript 只更改了一点内容,就是切换className. 动画使用css3 animation 做的,因此兼容IE10+ 除了javascript的改动之外,你需要添加一段css样式。
var imgHoverReplaceSrc = {
init: function (sel) {
this.sel = sel || "img";
this.imgList = document.querySelectorAll(sel);
this.work();
},
work: function () {
var _this = this;
this.imgList.forEach(function (item) {
item.addEventListener("mouseenter", function () {
_this.changeSrc(item);
item.className = "left";
});
item.addEventListener("mouseleave", function () {
_this.changeSrc(item);
item.className = "right";
});
});
},
changeSrc: function (item) {
if (item.getAttribute('data-src')) {
var tmpSrc = item.src;
item.src = item.getAttribute('data-src');
item.setAttribute('data-src', tmpSrc);
}
}
}
imgHoverReplaceSrc.init("img");
css样式:
img {
width: 100px;
height: 100px;
}
img.left{
animation: imgFadeFromLeft .5s ;
-webkit-animation: imgFadeFromLeft .5s ;
-moz-animation:imgFadeFromLeft .5s ;
-o-animation: imgFadeFromLeft .5s ;
}
img.right{
animation: imgFadeFromRight .5s ;
-webkit-animation: imgFadeFromRight .5s ;
-moz-animation:imgFadeFromRight .5s ;
-o-animation: imgFadeFromRight .5s ;
}
@keyframes imgFadeFromLeft {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-moz-keyframes imgFadeFromLeft {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-webkit-keyframes imgFadeFromLeft {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-o-keyframes imgFadeFromLeft {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@keyframes imgFadeFromRight {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-moz-keyframes imgFadeFromRight {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-webkit-keyframes imgFadeFromRight {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
@-o-keyframes imgFadeFromRight {
from{
opacity: 0;
transform:translateX(20px);
}to{
opacity:1;
transform:translateX(0px);
}
}
效果如下(加上动画):