DIV CSS 佈局教程網

用 JS 運動框架打造滑出的分享側邊欄動畫
編輯:JavaScript綜合知識     

很多網站的側邊都會放一個「分享到」的小掛件,滑鼠移入時它會滑出來、移出時再收回。本文就透過一個運動框架,示範如何實作這個流暢的分享側邊欄動畫,重點在於熟練操作 div 與 CSS 屬性。

基礎版本

先來看最直白的寫法,透過鼠標移入移出事件控制 div 的 left 屬性:

代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#div1{
width:319px;
height: 340px;
border: 1px solid #FFF;
position: absolute;
top:100px;
left:-320px;
background-image: url(images/1.png);
background-repeat:no-repeat ;
}
#div1 span{
width:30px;
height: 130px;
border: 1px solid blue;
position: absolute;
right:-23px;
top:95px;
background: red;
font-family: "微軟雅黑";
color: #FFFFFF;
text-align: center;
line-height: 40px;
border-radius: 0px 200px 200px 0px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById("div1");
var oSpan=oDiv.getElementsByTagName('span')[0];
var time=null;
var speed=8;
oDiv.onmouseover=function(){//這裡給整個div加鼠標移入的事件
clearInterval(time);
time=setInterval(function(){
if(oDiv.offsetLeft>=0){clearInterval(time);}
else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},1);
}
oDiv.onmouseout=function(){//這裡給整個div加鼠標移出事件
clearInterval(time);
time=setInterval(function(){
if(oDiv.offsetLeft<=-320){clearInterval(time);}
else{
oDiv.style.left=oDiv.offsetLeft-speed+'px';
}
},1);
}
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>

優化後的版本

上面的寫法有個小問題:移入與移出的邏輯幾乎重複。我們可以把運動過程抽成一個 move 函式,讓程式碼更精簡、更易維護:

代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#div1{
width:319px;
height: 340px;
border: 1px solid #FFF;
position: absolute;
top:100px;
left:-320px;
background-image: url(images/1.png);
background-repeat:no-repeat ;
}
#div1 span{
width:30px;
height: 130px;
border: 1px solid blue;
position: absolute;
right:-23px;
top:95px;
background: red;
font-family: "微軟雅黑";
color: #FFFFFF;
text-align: center;
line-height: 40px;
border-radius: 0px 200px 200px 0px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById("div1");
var oSpan=oDiv.getElementsByTagName('span')[0];
var time=null;
var spe=8;
var speed=null;
function move(bord){
clearInterval(time);
time=setInterval(function(){
if(oDiv.offsetLeft>bord){speed=-spe;}
else{speed=spe;}
if(oDiv.offsetLeft==bord){clearInterval(time);}
else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},1);
}
oDiv.onmouseover=function(){//這裡給整個div加鼠標移入的事件
move(0);
}
oDiv.onmouseout=function(){//這裡給整個div加鼠標移出事件
move(-320);
}
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>

透過把邊界值當作參數傳入,move 函式就能同時處理滑出與收回兩種情況,這也是運動框架的精髓所在。希望這個範例能為你的 JavaScript 動畫開發帶來啟發。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved