DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
CSS+DIV+JS 導覽選單:做出接近 Flash 的滑動質感
編輯:CSS詳解     

在 Flash 盛行的年代,這種「滑過就滑開、露出第二行文字」的按鈕幾乎都要靠向量軟體才做得出來。其實用 CSS 定位加上一個十幾行的 JavaScript 計時器,效果八九不離十。

結構:三層 div 組成一個按鈕

<div id=fbtn>
 <div id=fbtn_mask></div>
 <div id=fbtn_txt>
 <div>G1</div>
 <div>good morning</div>
 </div>
</div>

外層是外框,fbtn_txt 放兩行文字,fbtn_mask 則是一塊白色遮罩。動畫的原理就是讓文字往上滑、遮罩往下退,兩者錯開就會產生「拉開」的錯覺。

樣式

<style>
body{ background-color:#B8B8A0; }
#fbtn{
  display:none;
  overflow:hidden;
  border-style:solid;
  border-width:1px;
  border-color:#e1e1c9 #e1e1c9 #6e6e56 #6e6e56;
  padding:1 1 1 1;
  width:115px;
  height:30px;
}
#fbtn_txt{ position:relative; }
#fbtn_txt div{
  height:30px;
  padding-top:11px;
  font-size:9px;
  font-family:small fonts;
  color:#800080;
  text-align:center;
  cursor:hand;
}
#fbtn_mask{
  background-color:#ffffff;
  position:relative;
  width:100%;
  height:100%;
}
</style>

border-color 刻意寫成「上右下左」=亮、亮、暗、暗,做出凸起的外框;overflow:hidden 則是整個效果的前提,沒有它,滑出去的文字會露在框外。

動畫腳本

<script>
var current=null;
var t=null;
for(var i=0;i<fbtn.length;i++){
  fbtn_txt[i].style.posTop=-30;
  fbtn_mask[i].style.posTop=-30;
  fbtn[i].index=i;
  fbtn[i].style.display="block";
  fbtn[i].onmouseover=function(){
    if(!current){
      current=this;
      domove(this.index);
    }
    else if(current!=this){
      domove(current.index);
      domove(this.index);
      current=this;
    }
  }
  fbtn[i].onmouseout=function(){
    if(event.toElement==this.parentElement && t==this){
      domove(this.index);
      current=null;
    }
  }
}
function domove(num){
  var o=fbtn_txt[num];
  var m=fbtn_mask[num];
  if(o.style.posTop<-60){
    o.style.display="none";
    var t=o.children[1].innerHtml;
    o.children[1].innerHTML=o.children[0].innerHtml;
    o.children[0].innerHtml=t;
    o.style.posTop=-30;
    o.style.display="block";
    if(m.style.posTop>30) m.style.posTop=-30;
    else m.style.posTop=0;
  }
  else{
    m.style.posTop+=3;
    o.style.posTop-=3;
    setTimeout('domove('+num+')',15);
  }
}
</script>

逐段解讀

domove() 是靈魂。每一輪讓文字 posTop -= 3、遮罩 posTop += 3,再用 setTimeout 每 15 毫秒呼叫自己一次,於是每 15ms 移動 3px,換算出來約每秒 200px 的速度。

當文字位置超過 -60,代表它已經滑出可視範圍,這時做兩件事:把兩行文字的內容互換(children[0] 與 children[1] 對調),再把位置重置回 -30。所以第二次滑過時,你看到的是原本的第二行被換到第一行的位置——這正是「循環輪播」的效果。

onmouseout 裡的 event.toElement==this.parentElement 是為了避免滑鼠移到子元素時誤判為離開,屬於 IE 事件模型的寫法。

用今天的方式重寫會更省事

這段程式依賴 posTop(IE 專屬)、innerHtml(大小寫錯誤的拼法)與id 自動變全域變數,在標準瀏覽器上不會動。同樣的效果用 CSS transition 只要幾行:

<style>
.fbtn{width:115px;height:30px;overflow:hidden;border:1px solid #6e6e56;background:#fff}
.fbtn span{display:block;line-height:30px;text-align:center;color:#800080;
  transition:transform .3s;}
.fbtn:hover span{transform:translateY(-30px)}
</style>

交給瀏覽器的合成器處理動畫,不但平滑,也不必自己算座標與計時。

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