最近写个运动框架, 确实好用, 来附上, 具体就不说了, 注释比较详细
简洁版: 包括链式运动, 没有同时运动, 不需要 json 格式
- // 获取非行间样式
- function getStyle(obj,attr){
- if(obj.currentStyle){
- return obj.currentStyle[attr]
- }
- else{
- return getComputedStyle(obj,false)[attr]
- }
- }
- //startMove 运动函数 fn 为链式运动
- function startMove(obj,attr,target,fn){
- clearInterval(obj.timer)
- obj.timer=setInterval(function(){
- var getCur=0
- if(attr==opacity){ // 兼容透明度
- getCur=Math.round(parseFloat(getStyle(obj,attr))*100)
- }
- else{
- getCur=parseInt(getStyle(obj,attr))
- }
- var speed=(target-getCur)/8 // 缓动运动
- speed=speed>0?Math.ceil(speed):Math.floor(speed)
- if(getCur==target){
- clearInterval(obj.timer)
- if(fn){
- fn.call(obj) // 回调函数作用域指向 obj
- }
- }else{
- if(attr==opacity){
- obj.style.filter=alpha(opacity:+(getCur+speed)+)
- obj.style.opacity=(getCur+speed)/100
- }else{
- obj.style[attr]=getCur+speed+px
- }
- }
- },30)
- }
完整版: 包括链式运动同时运动, 涉及到同时运动则需要利用 json 辅助完成
- // 获取非行间样式
- function getStyle(obj,attr){
- if(obj.currentStyle){
- return obj.currentStyle[attr]
- }
- else{
- return getComputedStyle(obj,false)[attr]
- }
- }
- //startMove 运动函数 fn 为链式运动 json for in 循环
- function startMove(obj,json,fn){
- clearInterval(obj.timer)
- obj.timer=setInterval(function(){
- var flag=true // 设置一个标签
- for(var attr in json){
- var getCur=0
- if(attr==opacity){ // 兼容透明度
- getCur=Math.round(parseFloat(getStyle(obj,attr))*100)
- }
- else{
- getCur=parseInt(getStyle(obj,attr))
- }
- var speed=(json[attr]-getCur)/8 // 缓动运动
- speed=speed>0?Math.ceil(speed):Math.floor(speed)
- if(getCur!=json[attr]){ // 判断标签 要的是最后的值
- flag=false
- }
- if(attr==opacity){
- obj.style.filter=alpha(opacity:+(getCur+speed)+)
- obj.style.opacity=(getCur+speed)/100
- }else{
- obj.style[attr]=getCur+speed+px
- }
- }
- if(flag){ // 判断标签 设置在 for in 外面意思是 for in 到全部的 attr 才执行接下操作
- clearInterval(obj.timer)
- if(fn){
- fn.call(obj) // 回调函数作用域指向 obj
- }
- }
- },30)
- }
需要注意的几点
获取非行间样式, 注意浏览器的兼容问题
常用的 Math 方法 parseInt 等的转换
回调函数, 作用域的问题
json 格式
来源: http://www.bubuko.com/infodetail-2497357.html