Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Share the JavaScript sports framework

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

本篇内容介绍了"分享JavaScript运动框架"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

JavaScript的运动,即让某元素的某些属性由一个值变到另一个值的过程。如让div的width属性由200px变到400px,opacity属性由0.3变到1.0,就是一个运动过程。

实现运动要注意以下方面:

1. 匀速运动(改变left、right、width、height、opacity等属性)

2. 缓冲运动(速度是变化的)

3. 多物体运动(注意所有东西都不能共用,否则容易产生冲突,如定时器timer)

4. 获取任意属性值(封装一个getStyle函数)

5. 链式运动(串行)

6. 同时运动(并行,同时改变多个属性,需要使用 json)

封装好的getStyle函数,在下面的运动框架中会用到:

function getStyle(obj,attr){

if(obj.currentStyle){

return obj.currentStyle[attr]; //针对IE

}

else{

return getComputedStyle(obj,false)[attr]; //针对Firefox

}

}

万能的运动框架:

function Move(obj,json,callback){

var flag=true; //标志变量,为true表示所有运动都到达目标值

clearInterval(obj.timer);

obj.timer=setInterval(function(){

flag=true;

for(var attr in json){

//获取当前值

var curr=0;

if(attr=='opacity'){

curr=Math.round(parseFloat(getStyle(obj,attr))*100); //parseFloat可解析字符串返回浮点数//round四舍五入

}

else{

curr=parseInt(getStyle(obj,attr)); //parseInt可解析字符串返回整数

}

//计算速度

var speed=(json[attr]-curr)/10;

speed=speed>0?Math.ceil(speed):Math.floor(speed);

//检测是否停止

if(curr!=json[attr]){

flag=false; //有一个属性未达目标值,就把flag变成false

}

if(attr=='opacity'){

obj.style.filter='alpha(opacity:'+(curr+speed)+')'; //针对IE

obj.style.opacity=(curr+speed)/100; //针对Firefox和Chrome

}

else{

obj.style[attr]=curr+speed+'px';

}

}

if(flag){

clearInterval(obj.timer);

if(callback){

callback();

}

}

},30);

}

调用上述运动框架的实例:

var div_icon=document.getElementById('icon');

var aList=div_icon.getElementsByTagName('a');

for(var i=0;i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report