动画效果
当我们想做类似轮播图这种动画效果时,可以先封装好一个函数,如果想让谁拥有动画效果,直接调用就可以。
function aimate(obj, target, callback) {
// obj为动的盒子,target为滑动的目标距离
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var step = (target - obj.offsetLeft) / 10;
// 减缓效果步长公式,为以下时比较合适
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if(obj.offsetLeft == target) {
clearInterval(obj.timer);
// callback是回调函数,可以传进来函数,当动画执行结束后调用
if(callback) {
callback();
}
}
obj.style.left = obj.offsetLeft + step + 'px';
}, 15);
};
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="动画效果.js"></script>
<style>
.father {
width: 300px;
height: 300px;
background-color: aquamarine;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: blanchedalmond;
position: absolute;
left: 0;
}
</style>
</head>
<body>
<button>点击动</button>
<div class="father">
<div class="son"></div>
</div>
<script>
var son = document.querySelector('.son');
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
aimate(son, 1000);
});
</script>
</body>
</html>