首先引入匀速动画函数和变速动画函数
例如,点击按钮让元素移动到指定的位置。这里就要用到动画函数。动画函数里面需要用到定时器serInterval(要执行的函数,间隔时间)。
匀速动画函数:
function animation(element,target){//要移动的元素和终点
clearInterval(element.timeId);//上来先清除定时器--如果不清除,多点几下移动的按钮,移动速度会加快
var current = element.offsetLeft; //获取元素此时的距离左边的位置
var step = 10; //因为是匀速动画函数,所以规定每次移动的距离
step = (target-current)>0?step:-step;
element.timeId = setInterval(function(){
//目的是如果到目标的距离小于移动的步数,就移动剩下的距离就好,不用移动指定的步数
if(Math.abs(target-current)>Math.abs(step)){
current+=step;
element.style.left = current + "px";
}else{
element.style.left = target + "px";
clearInterval(element.timeId);
}
},20);
}
变速动画函数:
function animation(element,target){//要移动的元素和终点
clearInterval(element.timeId);//上来先清除定时器--如果不清除,多点几下移动的按钮,移动速度会加快
var current = element.offsetLeft; //获取元素此时的距离左边的位置
element.timeId = setInterval(function(){
var step = (target-current)/10; //变速动画函数,距离越大,移动的越多
step = step>0?Math.ceil(step):Math.floor(step);//移动的步数是整数比较好
console.log(step);
current+=step;
element.style.left = current + "px";
if(target==current){
clearInterval(element.timeId);
}
},20);
}
1. 旋转木马
思路:
① 页面加载时,各个图片移动到各自的位置。
② 鼠标经过时,左右按钮出现。离开时隐藏。
③ 点击按钮,各个图片分别移动到相应的位置。