前些日子看了個視頻所以就模仿它的技術來為大家做出幾個簡單的JS小特效
今天為大家做的是多個物體的運動效果,
1:HTML
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
2:css
<style type="text/css">
body,*{margin: 0;padding: 0;}
ul{list-style: none;}
ul li{width:300px;height: 100px;background: red;margin-top: 20px;}
</style>
3:javascript部分
<script type="text/javascript">
window.onload=function(){ //頁面加載完畢執行匿名函數
var allLi=document.getElementsByTagName("li"); /*獲取所有li標簽*/
for(var i=0;i<allLi.length;i++){ /*遍歷每個li并為每個li添加事件*/
allLi[i].timer; /*為每個li創建一個定時器容器*/
allLi[i].onmouseover=function(){
onOut(this,400); /*調用函數并把當前的li作為參數方便函數體調用當前li*/
}
allLi[i].onmouseout=function(){
onOut(this,300);
}
}
}
function onOut(that,width){
clearInterval(that.timer); /*每次函數被調用的時候都先清空一下定時器*/
that.timer=setInterval(function(){ /*函數調用時執行定時器 注意 這里我們為每個Li元素都定義了屬于自己的一個定時器,防止了大家公用同一個定時器而造成的動畫效果不一致問題*/
var speed=(width-that.offsetWidth)/5; /*定義變化的速度*/
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(that.offsetWidth==width){ /*到達目標寬度的時候刪除定時器,防止無限變寬*/
clearInterval(that.timer);
}else{ that.style.width=that.offsetWidth+speed+"px";} /*把當前Li的寬度定義為當前Li的寬度+預先定義好的寬度*/
},10)
}
</script>
效果
現在我們改一個效果,多個物體的透明度變化
1:HTML
<body>
<div></div>
<div></div>
<div></div>
</body>
2:CSS
<style type="text/css">
body,*{margin: 0;padding: 0;}
div{width: 250px;height: 250px;float: left;margin: 5px;background: blue;filter:alpha(opacity:20);opacity:0.2 }
</style>
3:JS
<script type="text/javascript">
window.onload=function(){
var div=document.getElementsByTagName("div");
for(var i=0;i<div.length;i++){
div[i].onmouseover=function(){
onOut(this,100);
}
div[i].onmouseout=function(){
onOut(this,20);
}
div[i].opa=20; /*為每個div設置一個透明度的屬性 值得注意的的是多物體的運動的多有變量都不能公用以防止資源爭用*/
}
}
var timer;
function onOut(that,tar){
clearInterval(that.timer);
var speed;
that.timer=setInterval(function(){ /*為每個div創建自己的定時器*/
if(tar>that.opa){
speed=+10;
}else{
speed=-10;
}
if(that.opa==tar){
clearInterval(timer);
}
else{
that.opa+=speed;
that.style.opacity=that.opa/100;
that.style.filter="alpha(opacity:'+that.opa+')";
}
},20)
}
</script>
效果
文章列表