您的位置:首页 > Web前端 > JavaScript

js 运动框架(一)匀速运动

2014-08-22 17:32 507 查看
一、匀速运动

元素向左向右滑动,以漂浮的“分享到”为例。鼠标滑到分享到,其内容展开(向右滑动),鼠标移出,其内容收起(向左滑动)。





<body>
<div id="div1">
<div id="div2">分享到</div>
</div>
</body>


加样式,两个div都是绝对定位的,不然不能运动。

#div1{width: 120px;height: 250px;position: absolute;top:100px;left:-120px;background: #ccc;}
#div2{width: 30px;text-align:center;position: absolute;left:120px;top:80px;background: yellow;}


js中,得到div1,给其鼠标滑动添加事件,运动中必须用到的是定时器。

伪代码:

var timer;

div1.onmouseover=function(){

timer=setInterval(function(){

若left<0,left+=5;

若>=0,停止,清除定时器。

},30);

div1.onmouseout=function(){

timer=setInterval(function(){

若left>-120,left-=5;

若<=0,停止,清除定时器。

},30);

两段代码十分相似,把其中不同的变量设为参数,就可以抽象出一个函数。在这里,速度的方向和终止的位置不同。

运动框架:

在开始运动时,关闭已有定时器。

用(if/else)把运动和停止分开。

var timer=null;
function startMove(iSpeed,iTarget){
clearInterval(timer);
var oDiv=document.getElementById('div1');
timer=setInterval(function(){
if(oDiv1.offsetLeft==iTarget){
clearInterval(timer);
}
else{
oDiv1.style.left= oDiv1.offsetLeft+iSpeed+'px';
}
},30);
}
但是我们希望有更少的参数,我们其实可以自己判断速度,当left比终点小,速度是5,否则是-5。简化后:

<pre name="code" class="javascript">var timer=null;
function startMove(iTarget){
clearInterval(timer);
var oDiv1=document.getElementById('div1');
var iSpeed=0;
if(oDiv1.offsetLeft<iTarget){
iSpeed=5;
}
else{
iSpeed=-5;
}
timer=setInterval(function(){
if(<span style="font-family: Arial, Helvetica, sans-serif;">oDiv1.offsetLeft</span>==iTarget){
clearInterval(timer);
}
else{			<pre name="code" class="javascript"><span style="white-space:pre">			</span>oDiv1.style.left= oDiv1.offsetLeft+iSpeed+'px';
}},30);}





图片淡入淡出:





<script type="text/javascript">
var timer=null;
var alpha=30;  //不能直接得到图片透明度,所以需要变量存储透明度
function startMove(iTarget){
clearInterval(timer);
var oImg=document.getElementById('img1');
var speed=0;
if(alpha<iTarget){
speed=5;
}
else{
speed=-5;
}
timer=setInterval(function(){
if(alpha==iTarget){
clearInterval(timer);
}
else{
alpha+=speed;
oImg.style.filter='alpha(opacity)'+alpha+')';   //兼容ie
oImg.style.opacity=alpha/100;
}

},30);
}
window.onload=function(){
var oImg=document.getElementById('img1');
oImg.onmouseover=function(){
startMove(100);
}
oImg.onmouseout=function(){
startMove(30);
}
}
</script>


#img1{width: 300px;filter: alpha(opacity:30);opacity: 0.3;}


<img id="img1" src="img/Koala.jpg"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: