js运动框架封装以及两种案例
2018-10-22 09:59 小花儿鹿 阅读(297) 评论(0) 编辑 收藏 举报1、sports.js代码
function sport(obj,json,fn){ //1.先停止上一次的计时器 clearInterval(obj.timer); //2.开启新的计时器 obj.timer = setInterval(()=>{ //1.设置开关 let stop = true; //2.遍历json for(let attr in json){ //1.获取当前值 let cur = attr === 'opacity' ? parseInt(parseFloat(getStyle(obj,attr) )* 100) : parseInt(getStyle(obj,attr)); //2.计算速度 let speed = (json[attr] - cur) / 8; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //3.判断是否结束 if(cur !== json[attr]){ stop = false; } //4.设置运动 if(attr === 'opacity'){ obj.style.opacity = (cur + speed) / 100; obj.style.filter = "alpha(opacity=" + (cur + speed) + ")"; }else{ obj.style[attr] = cur + speed + 'px'; } } if(stop){ clearInterval(obj.timer); if(typeof fn === 'function'){ fn(); } } },30) }
//获取非行内样式(兼容)
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,1)[attr];
}
2.1、多物体运动(非链式)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <style type="text/css"> body{ height: 5000px; } div{ width: 100px; height: 100px; background: red; border: 2px solid black; opacity: 1; filter: alpha(opacity=100); } </style> </head> <body> <div></div> <script src="sport.js"></script> <script type="text/javascript"> const oDiv = document.querySelectorAll('div')[0]; oDiv.onmouseenter = function(){ sport(this,{width : 400,height:400,opacity:30}); } oDiv.onmouseleave = function(){ sport(this,{width : 100,height : 100,opacity : 100}); } </script> </body> </html>
2.2、多物体运动(链式)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <style type="text/css"> #box{ width: 100px; height: 100px; background: red; opacity: 1; filter: alpha(opacity=100); } </style> </head> <body> <div id="box"> </div> <script src="sport.js"></script> <script type="text/javascript"> let oDiv = document.getElementById("box");
//箭头函数 oDiv.onmouseenter = function(){ sport(this,{width : 300},()=>{ sport(this,{height : 300},()=>{ sport(this,{opacity : 30}) }) }); }
//bind oDiv.onmouseleave = function(){ sport(this,{opacity : 100},function(){ sport(this,{height : 100},function(){ sport(this,{width : 100},"hehe") }.bind(this)) }.bind(this)) } </script> </body> </html>