本文分析了JS实现多目标运动的方法。分享给大家参考,如下:
基本步骤
1.通过getElementsByTagName获取要进行多对象移动的元素。2.然后循环遍历元素以添加事件。3.定义startMove函数,这需要两个参数,当前的“移动”元素和目标值。
注意:在多物体运动中,一切都不能共享;
script window . onload=function(){ var liTags=document . getelementsbytagname(' Li ');//第一步为(var I=0;军事集团.长度;I){//step 2 litages[I]。onmouseover=function(){ start move(this,400);} liTags[i]。onmouseout=function(){ startMove(this,200);} } } var timer=null函数start move (obj,itar get){//第三步,两个参数clearInterval(定时器);timer=setInterval(function(){ var iSpeed=(itar get-obj . offsetwithts)/10;iSpeed=iSpeed0?math . ceil(I speed): ath . floor(I speed);//注意舍入if (obj。offset witth==itar get){ clear interval(timer);} else { obj . style . width=obj . offsetidth is feed ' px ';} },30);}/脚本问题:
当进出的速度比较快的时候,会有一些li无法回到原来的样子,中途卡住;这是因为所有李的共享一个定时器。
当鼠标移动到第一个li时,调用startMove启动定时器;当鼠标移开li时,也需要启动定时器,使li返回到原来的位置。当li在中途时,我们移动第二个li,计时器将首先被清除,然后第一个li在中途卡住。
解决这个问题:让每个li拥有自己的定时器来控制它们的变化,并在for循环中为每个Li定义自己的定时器
liTags[i]。timer=null//给每个li添加一个定时器,然后每次在starMove中使用的定时器都是当前li自己的,这样就不会互相干扰了。
这里,从前一个计时器到obj.timer(当前对象自己的计时器);这里没问题。
完整的代码如下:
body ul Li/Li Li/Li Li/Li Li/Li Li/ul/body虚线样式:
样式ul { list-style : none;} ul li { margin: 10px宽度: 200 px;高度: 50px;背景:浅蓝色;}/style完整的js代码
script window . onload=function(){ var liTags=document . getelementsbytagname(' Li ');for(var I=0;军事集团.长度;i ){ liTags[i]。timer=null//增加一个定时器litags [I]。onmouseover=function(){开始移动(这个,400)到每个Li;} liTags[i]。onmouseout=function(){ startMove(this,200);} } }函数startMove(obj,itar get){ clearInterval(obj . timer);obj . timer=setInterval(function(){ var iSpeed=(iTarget-obj . offsetwithts)/10;iSpeed=iSpeed0?math . ceil(I speed): ath . floor(I speed);if(obj . offsetidth==itar get){ clearInterval(obj . timer);} else { obj . style . width=obj . offsetidth is feed ' px ';} },30);}/script然后看一个例子:多对象运动改变透明度
脚本窗口。onload=function(){ var AIMgs=document。getelementsbytagname(' img ');for(var I=0;iaimgs . lengthi){ aimmgs[I].timer=nullaImgs[i],=100;//把公用的希腊字母的第一个字母改成每个图片对象都有的属性目标.onmouseover=function(){ startMove(this,30);我.onmouseout=function(){ startMove(this,100);} } }//var alpha=100;这里希腊字母的第一个字母在多物体运动里不能公用函数startMove(obj,itar get){ clearInterval(obj。计时器);var iSpeed=(itar get-obj。)/10;iSpeed=iSpeed0?数学天花板:数学地板;物体。timer=setInterval(function(){ if(obj。alpha==itar get){ clearInterval(obj。计时器);} else { obj.alpha=iSpeedobj。风格。不透明度=obj。/100;物体。风格。filter=' alpha(opa city 3360 ' obj。alpha ')';} },30);}/脚本更多关于Java脚本语言相关内容感兴趣的读者可查看本站专题: 《JavaScript运动效果与技巧汇总》 、 《JavaScript切换特效与技巧总结》 、 《JavaScript查找算法技巧总结》 、 《JavaScript动画特效与技巧汇总》 、 《JavaScript错误与调试技巧总结》 、 《JavaScript数据结构与算法技巧总结》 、 《JavaScript遍历算法与技巧总结》 及《JavaScript数学运算用法总结》
希望本文所述对大家Java脚本语言程序设计有所帮助。