匀速动画:
在浏览器中,某一个盒子元素以稳定不变的速度向某个方向移动直到停止
效果展示
代码部分
html+css
<style>
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
</style>
<body>
<input type="button" id="move400" value="移动到400">
<div id="box"></div>
</body>
js 已封装 可直接调用
运用元素绝对定位的 top left 等属性 来修改盒子元素的位置
<script>
var btn = document.getElementById("move400");
var box = document.getElementById("box");
// 声明变量保存定时器ID
var timeID = null;
// var currentLeft = box.offsetLeft;
btn.onclick = function(){
Animation(box,400);
};
/*
解决移动方向的问题
出现问题 :元素从左往右移动 是匀速移动,但是从右往左没有动画
分析问题 :
从左往右,currentLeft < target currentLeft +=10,
从右往左,currentLeft > target currentLeft -=10
解决问题 :做方向判断
*/
//封装
function Animation(ele, target){
// 开启一个定时器之前 先清除原本存在的定时器
clearInterval(ele.timeID);
ele.timeID = setInterval(function(){
// 获取当前位置
var currentLeft = ele.offsetLeft;
// 判断
// if(currentLeft < target){
// var isLeft = true; //从左往右
// } else {
// var isLeft = false; //从右往左
// }
//三元表达式判断
var isLeft = currentLeft < target? true : false;
// 判断移动盒子是加还是减
// if(isLeft) {
// // 移动盒子
// currentLeft += 12;
// } else {
// // 移动盒子
// currentLeft -= 12;
// }
//三元表达式判断
isLeft?currentLeft += 12:currentLeft -= 12;
// 把盒子现在的位置赋值非left属性
ele.style.left = currentLeft + "px";
// 边界检测
if(isLeft) {
if(currentLeft >= target){
// 停止运动 :清除定时器
clearInterval(ele.timeID);
// 元素复原
ele.style.left = target + "px";
}
} else{
if(currentLeft <= target){
// 停止运动 :清除定时器
clearInterval(ele.timeID);
// 元素复原
ele.style.left = target + "px";
}
}
},50)
}
</script>
缓动动画:
在浏览器中,某一个盒子以一个从快到慢的速度向右移动直到停止
动画效果
代码部分
html+css
<style>
#box {
width: 100px;
height: 100px;
background-color: greenyellow;
position: absolute;
left: 0;
top: 100px;
}
</style>
<body>
<input type="button" value="缓速移动到400" id="move400">
<div id="box"></div>
</body>
jsf (已封装 可直接调用)
缓动动画与匀速动画的不同就在于多用了一个公式:
从左往右 目标位置 > 当前位置 speed = (目标位置 - 当前位置) / 10 得到的是 > 0 的数 向上取整
从右往左 目标位置 < 当前位置 speed = (目标位置 - 当前位置) / 10 得到的是 < 0 的数 向下取整
一般将缓动系数 /10 是为了让动画移动更加细腻
<script>
// 1.控制多个运动,复制代码 代码冗余 ---封装函数
// 2.移动距离的问题 -- 传参
// 3.多和元素同时移动
// 4.移动方向
/*
缓动可以自动实现从左往右和从右往左:
发现问题: 缓动可以自动实现方向的问题 但是从左往右没有误差 从右往左有误差
分析问题:
从左往右 目标位置 > 当前位置 speed = (目标位置 - 当前位置) / 10 得到的是 > 0 的数 向上取整
从右往左 目标位置 < 当前位置 speed = (目标位置 - 当前位置) / 10 得到的是 < 0 的数 向下取整
*/
//1.获取元素
var btn = document.getElementById("move400");
var box = document.getElementById("box");
var timeID = null;
//缓速运动
// 2.注册点击事件
btn.onclick = function () {
slowMowe(box,400);
}
function slowMowe(ele,target) {
//3.开启定时器
clearInterval(timeID);
timeID = setInterval(function () {
// 3.1获取元素当前
var oldLeft = ele.offsetLeft;
//3.2开始匀速运动
//消除误差
var speed = (target - oldLeft) / 10;
speed = speed > 0?Math.ceil(speed):Math.floor(speed);
oldLeft += speed;
//3.3讲移动到的
ele.style.left = oldLeft + "px";
//终点检测
if (oldLeft == target) {
//停止运动清除定时器
clearInterval(timeID);
}
}, 50)
}
</script>