给大家分享一个抖动的小案列
代码如下欢迎大家留下你的意见和改进方案
<body>
<img style="position: absolute; left:200px; top: 100px;" src="./img/meinv1.webp" alt="">
<img style="position: absolute; left:600px; top: 100px;" src="./img/meinv2.webp" alt="">
</body>
<script>
var oimg1 = document.getElementsByTagName("img")[0]
var oimg2 = document.getElementsByTagName("img")[1]
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj)[attr];
}
}
// alert(getStyle(oimg1, "left"))
oimg1.onclick =doudong
oimg2.onclick =doudong
function doudong(){
_this=this
moveing( _this,"top",function(){
moveing (_this,"left")
})
}
function moveing(obj,arrt,endObj){
var num = 0
var arr = []
var timer = null;
clearInterval(timer)
for (i = 20; i > 0; i -= 2) {
arr.push(i, -i)
}
arr.push(0)
timer = setInterval(function(){
// console.log(arr)
obj.style[arrt] = parseInt(getStyle(obj, arrt)) + arr[num] + "px"
num++
if(num == arr.length){
clearInterval(timer)
endObj && endObj()
}
// console.log(num)
}, 50)
}
</script>