<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.onload=function(){
var oImg1=document.getElementById('img');
var oImg2=document.getElementById('img2');
var iOld=getStyle(oImg1,'left');
var iOld2=getStyle(oImg2,'top');
oImg1.onclick=function(){
this.style.left=iOld; //每次点击时,都把目标的left初始化
shake(this,'left',20)
}
oImg2.onclick=function(){
this.style.top=iOld2;
shake(this,'top',20)
}
function shake(obj,attr,ispeed,endFn){
var iLeft=parseInt(getStyle(obj,attr));
var arr=[];
var timer=null;
var num=0;
for (var i = ispeed; i > 0; i-=2) {
arr.push(i,-i)
};
console.log(arr)
clearInterval(obj.timer);
obj.timer=setInterval(function(){
obj.style[attr]=iLeft+arr[num]+'px';
num++;
console.log(iLeft)
if (num==arr.length) {
console.log('aa'+iLeft)
clearInterval(obj.timer);
obj.style[attr]=iLeft+'px'; //暂停之时等于原来的ileft。必须有
endFn && endFn();
};
},50)
}
}
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr];
}
</script>
</head>
<body>
<span style="display:block;width:1px;height:800px;background:#000;position:absolute;left:300px;top:0;"></span>
<img src="img/3.png" width="100px" height="200px" id="img" style="position:absolute;left:300px;top:70px">
<img src="img/4.png" width="100px" height="200px" id="img2" style="position:absolute;left:700px;top:70px">
</body>
</html>
图片抖动
最新推荐文章于 2023-11-18 10:01:02 发布