DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
用 CSS+少量 JavaScript 做一個帶提示的酷炫選單
編輯:CSS詳解     

這個效果有兩個亮點:滑過時整列反白,同時下方淡入一段說明文字。視覺靠 CSS,淡入靠一點點 opacity 動畫。

head 區:選單與提示框的樣式

<!-- 把下列代碼加入到 head 區內 -->
<style type="text/css">

#coolmenu{
  border: 1px solid black;
  width: 170px;
  background-color: #E6E6E6;
}

#coolmenu a{
  font: bold 13px Verdana;
  padding: 2px 2px 2px 4px;
  display: block;
  width: 100%;
  color: black;
  text-decoration: none;
  border-bottom: 1px solid black;
}

/* 修正 IE 的 box model 造成的溢出 */
html>body #coolmenu a{ width: auto; }

#coolmenu a:hover{
  background-color: black;
  color: white;
}

#tabledescription{
  width: 100%;
  height: 3em;
  padding: 2px;
  filter: alpha(opacity=0);   /* IE */
  -moz-opacity: 0;            /* 舊 Firefox */
}
</style>

淡入腳本

<script type="text/javascript">
var baseOpacity = 0;

function showtext(thetext){
  if (!document.getElementById) return;
  var box = document.getElementById("tabledescription");
  var isIE = !!box.filters;
  var isMoz = (typeof box.style.MozOpacity == "string");

  instantset(baseOpacity);
  box.innerHTML = thetext;
  highlighting = setInterval(function(){ gradualfade(box); }, 50);
}

function hidetext(){
  clearInterval(highlighting);
  instantset(baseOpacity);
}

function instantset(degree){
  if (isMoz)      box.style.MozOpacity = degree / 100;
  else if (isIE)  box.filters.alpha.opacity = degree;
  else if (baseOpacity == 0)
    document.getElementById("tabledescription").innerHTML = "";
}

function gradualfade(cur){
  if (isMoz && cur.style.MozOpacity < 1)
    cur.style.MozOpacity = Math.min(parseFloat(cur.style.MozOpacity) + 0.2, 0.99);
  else if (isIE && cur.filters.alpha.opacity < 100)
    cur.filters.alpha.opacity += 20;
  else
    clearInterval(highlighting);
}
</script>

body 區:掛上事件

<!-- 把下列代碼加入到 body 區內 -->
<div id="coolmenu">
  <a href="https://www.knowsky.com"
     onmouseover="showtext('JavaScript tutorials and scripts!')"
     onmouseout="hidetext()">knowsky.com</a>
  <a href="https://www.knowsky.com/JS/"
     onmouseover="showtext('300+ free JavaScripts')"
     onmouseout="hidetext()">knowsky.com</a>
  <a href="https://bbs.knowsky.com"
     onmouseover="showtext('Web coding and development forums!')"
     onmouseout="hidetext()">knowsky Forums</a>

  <div id="tabledescription"></div>
</div>

用現代寫法重做同一個效果

那段 MozOpacity 與 filters.alpha 的分支判斷,今天可以整段刪掉—— opacity 已是標準屬性,動畫交給 CSS:

#tabledescription{
  opacity: 0;
  transition: opacity .3s ease;
}
#tabledescription.show{ opacity: 1; }

// 只需要切換 class
function showtext(t){
  var box = document.getElementById("tabledescription");
  box.textContent = t;
  box.classList.add("show");
}
function hidetext(){
  document.getElementById("tabledescription").classList.remove("show");
}

另外原版的 box 變數寫在函式外,多個選單快速滑過時容易出錯;改用 var box = ... 宣告在函式內,就不會互相干擾。這也是為什麼同一段邏輯值得每隔幾年重寫一次。

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