4 动画函数封装
4.1 动画原理实现
<style>
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<body>
<div></div>
<script>
var div = document.querySelector('div');
var timer = setInterval(function() {
if (div.offsetLeft >= 400) {
//停止动画,停止定时器
clearInterval(timer);
}
div.style.left = div.offsetLeft + 1 + 'px'; //offsetLeft只可以读,不可以写
}, 30)
</script>
</body>
4.2 动画函数简单封装
<style>
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
span {
position: absolute;
left: 0;
top: 200px;
display: block;
width: 150px;
height: 150px;
background-color: purple;
color: #fff;
}
</style>
<body>
<div></div>
<span>夏雨荷</span>
<script>
//简单动画封装 obj目标对象;target目标位置
function animate(obj, target) {
var timer = setInterval(function() {
if (obj.offsetLeft >= target) {
//停止动画
clearInterval(timer);
}
obj.style.left = obj.offsetLeft + 1 + 'px';
}, 30)
}
var div = document.querySelector('div');
var span = document.querySelector('span');
//调用函数
animate(div, 300);
animate(span, 200);
</script>
</body>
5 常见网页特效案例