很早的时候看过一个筋斗云的案例,当时刚接触动画,用的都是封装的animate函数,如今看来,css3的属性之一transition也能又快又简便的实现此动画,下面,我们就来看看吧~
实现的效果
区别在js部分
- html
<div class="nav"><span id="cloud"></span><ul id="navBar"><li>北京校区</li><li>上海校区</li><li>广州校区</li><li>深圳校区</li><li>武汉校区</li><li>关于我们</li><li>联系我们</li><li>招贤纳士</li></ul>
</div>
- css
* {margin: 0;padding: 0
}ul {list-style: none
}body {background-color: #333;
}.nav {width: 800px;height: 42px;margin: 100px auto;background: url(images/rss.png) right center no-repeat;background-color: #fff;border-radius: 10px;position: relative;
}.nav li {width: 83px;height: 42px;text-align: center;line-height: 42px;float: left;cursor: pointer;
}.nav span {position: absolute;top: 0;left: 0;width: 83px;height: 42px;background: url(images/cloud.gif) no-repeat;
}ul {position: relative;
}
- js
animate函数方法
//根据id获取对应的元素
function my$(id) {return document.getElementById(id);
}
/*
* element----要移动的元素
* target----移动的目标
*
* */
function animate(element,target) {clearInterval(element.timeId);element.timeId=setInterval(function () {//获取当前的位置var current=element.offsetLeft;//每次移动多少步var step=(target-current)/10;//(目标-当前)/10step=step>0?Math.ceil(step):Math.floor(step);current=current+step;element.style.left=current+"px";if(current==target){clearInterval(element.timeId);}console.log("target:"+target+"current:"+current+"step:"+step);},10);
}var nav=document.body.children[0];
var cloud=my$("cloud");
var ul=my$("navBar");
var lis=ul.children;
for(var i=0;i<lis.length;i++){lis[i].onmouseover=onmouseoverHandle;lis[i].onmouseout=onmouseoutHandle;lis[i].onclick=onclickHandle;
}
function onmouseoverHandle(){animate(cloud,this.offsetLeft);
}
var currentLeft=0;
function onclickHandle(){currentLeft=this.offsetLeft;
}
function onmouseoutHandle(){animate(cloud,currentLeft);
}
css3属性实现
而css3属性只需要加一个属性,改一个属性即可
.nav span {position: absolute;top: 0;left: 0;width: 83px;height: 42px;background: url(images/cloud.gif) no-repeat;transition: all .5s; //表示span的所有属性值发生改变的时候,会有0.5秒的动画
}var nav=document.body.children[0];
var cloud=my$("cloud");
var ul=my$("navBar");
var lis=ul.children;
for(var i=0;i<lis.length;i++){lis[i].onmouseover=onmouseoverHandle;lis[i].onmouseout=onmouseoutHandle;lis[i].onclick=onclickHandle;
}
function onmouseoverHandle(){cloud.style.left = currentLeft+'px';
}
var currentLeft=0;
function onclickHandle(){currentLeft=this.offsetLeft;
}
function onmouseoutHandle(){cloud.style.left = currentLeft+'px';
}