您的位置:首页 > Web前端 > JavaScript

js动画(3)——缓冲动画

2016-02-18 22:21 603 查看
<pre name="code" class="html"><!DOCTYPE = html>
<html>
<head>
<title></title>
<style>
body{
margin: 0px;
padding: 0px;
}

.red{
background-color:red;
width:200px;
height:200px;
position:relative;
left:-200px;
top:0px;
}

.blue{
background:blue;
width:20px;
height:50px;
position:absolute;
left:200px;
top:75px;
}
</style>
<script src="file:///F:front end/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div class="red" id="cf1"><div class="blue" id="cf">分享</div></div>
<script>
window.onload = function(){
var onDiv = document.getElementById("cf1");
onDiv.onmouseover = function(){
startmove(0);
}
onDiv.onmouseout = function(){
startmove(-200);
}
}
var timer ;
function startmove(target){
clearInterval(timer);//清除定时器,以免多次触发定时器导致速度越来越快而不是匀速前进
var onDiv1 = document.getElementById("cf1");
timer = setInterval(function(){
var speed = (target-onDiv1.offsetLeft)/10;
speed = speed>0?Math.ceil(speed):Math.floor(speed);//避免当不为整数个像素时,无法移动出现误差的情况
if(onDiv1.offsetLeft==target){
clearInterval(timer);
}
// speed = Math.floor(speed);
else{
onDiv1.style.left = onDiv1.offsetLeft+speed+'px';
}
},30)
}
</script>
</body>
</html>


小结:

1、这个例子和第一个例子很类似,区别在于速度的变化(越接近目标速度越低);

2、由于速度在设置时已经确定了符号,所以不用分情况讨论;

3、为啥speed大于0时向上取整,小于0时候向下取整,要想清楚。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  前端 js动画 css