html
<img src="images/doudong.jpg" id="img" alt="" />
<img src="images/doudong.jpg" id="img1" alt="" />
js
function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
var oimg=document.getElementById("img");
var oimg1=document.getElementById("img1");
// oimg.onclick=function(){
// var _this=this;
// shake(_this,'left',function(){
// shake(_this,'top') //匿名函数没人调用 如果此写this指的是window
// })
// };
function fnShake(){
var _this=this;
shake(_this,'left',function(){
shake(_this,'top')
})
};
oimg.onclick=fnShake;
oimg1.onclick=fnShake;
function shake(obj,attr,endFn){
var pos=parseInt(getStyle(obj,attr));
var arr=[];
for(i=20;i>0;i-=2){
arr.push(i,-i);
}
arr.push(0);
var num=0;
//var timer=null;
clearInterval(obj.shake);
obj.shake=setInterval(function(){
obj.style[attr]=pos+arr[num]+'px';
num++;
if(num===arr.length){
clearInterval(obj.shake);
endFn && endFn();
}
},50)
}
css
img{ 200px;height: 200px;position: relative;left: 500px;}
img1{ 200px;height: 200px;position: relative;left: 600px;}