原生JS实现封装的抖动函数框架
<style>
ul{ margin-top: 100px; }
li {
float: left;
margin-left: 20px;
position: absolute;
top: 0;
margin-top: 100px;
}
</style>
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
<script>
var oLi = document.getElementsByTagName('li');
for (var i = 0; i < oLi.length; i++) {
oLi[i].style.left = i + '10px';
oLi[i].onmouseover = function () {
var _this = this;
shake(_this, 'top', 20, function () {
alert('回调已完成')
})
}
}
//抖动运动框架
function shake(obj, attr, speed, endFn) {
if (obj.onoff) return; //当前的onoff=false
obj.onoff = true;
var pos = parseInt(getStyle(obj, attr));
var arr = []; //10,-10,8,-8,6,-6......
var timer = null;
var num = 0;
for (var i = speed; i > 0; i -= 2) {
arr.push(i, -i);
}
arr.push(0); //最后加上0
obj.timer = setInterval(function () {
obj.style[attr] = pos + arr[num] + 'px';
num++;
if (num === arr.length) {
clearInterval(obj.timer);
endFn && endFn();//判断回调函数
obj.onoff = false;
}
}, 50)
}
//获取css样式
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj)[attr];
}
}
</script>