JS轮播图前言animate.js函数的封装
先放一个小damo,效果用IE查看
鼠标点击盒子实现盒子的移动(JS实现)
控制台打印的数字是盒子与左边缘网页的距离。
HTML+CSS+JS 实现(匀速、变速)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>damo</title>
<style>
#box{
width: 100px;
height: 100px;
position: absolute;
left: 600px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script>
var box=document.getElementById("box")
box.onclick=function(){
var timer=setInterval(function(){
//鼠标点击打开定时器
//匀速
// var now=parseInt(getStyle(box,'left'));//注意转化为整型
// console.log(now); //查看是否获取到left值
// if(now==100){
// clearInterval(timer) // 清空定时器
// }else{
// box.style.left=now+1+"px";
// }
//变速
var now=parseInt(getStyle(box,'left'))
// var speed=Math.ceil((500-now)/6); //第一步优化向下取整,万一除不尽就一直到不了500(从左往右)
//进而优化从右往左
var speed=(333-now)/6;
if(speed>0){
speed=Math.ceil(speed);
}else{
speed=Math.floor(speed);
}
if(now==333){
clearInterval(timer);
}else{
box.style.left=now+speed+'px';
}
console.log(now)
},300)
}
function getStyle(obj,attr){ //获取样式
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return obj.getComputedStyle(obj,null)[attr]
}
}
</script>
</html>
那么同时想改变盒子的两种状态呢?比如让盒子一边运动一边改变它的透明值呢?
封装一个animate.js吧,用的时候直接传参数就好了。
现在我想让我的盒子从左上方跑到右下方并且透明度改变:
放函数:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>index</title>
<style>
#box{
width: 100px;
height: 100px;
position: absolute;
left: 0px;
top:0px;
background-color: red;
}
</style>
<script src="js/animate.js"></script>
</head>
<body>
<div id="box"></div>
</body>
<script>
var box=document.getElementById("box")
box.onclick=function(){
animate(box,{left:300,top:200,opacity:20},function(){
console.log("finish")
});
}
</script>
</html>
放核心函数(JS原生轮播使用):
//封装animate函数
function getStyle(obj,attr){ //获取样式
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return obj.getComputedStyle(obj,null)[attr]
}
}
function animate(obj,json,callback){
clearInterval(obj.timer); //控制多次点击不重定义定时器
obj.timer=setInterval(function(){
var isStop=true; //判断是否所有运动完成
for(var attr in json){
var now=0;
if(attr=='opacity'){
now=parseInt(getStyle(obj,attr)*100)
}
else{
now=parseInt(getStyle(obj,attr))
}
var speed=(json[attr]-now)/6;
if(speed>0){
speed=Math.ceil(speed);
}else{
speed=Math.floor(speed);
}
var current=now+speed;
if(attr=='opacity'){
obj.style[attr]=current/100;
}
else{
obj.style[attr]=current+'px';
}
if (json[attr] != current) { //任意一个定义的最后的动画值与当前值不等,不停止移动
isStop=false;
}
}
if(isStop==true){
clearInterval(obj.timer); //动画完成清除定时器
if(callback){
callback();
};
}
},0.1)
}
对比一下就能很好的理解啦~
下一篇:JS原生轮播图(带原理、思考步骤、详情)