萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現頂部可摺疊菜單工具列(滑鼠滑入展開)

效果描述

頁面頂部固定一條工具列,預設收合(僅露出標籤),滑鼠移入時向下滑出展開完整選單,移出延遲後自動滑回收合,類似早期入口網站頂部導航。

核心程式碼(自製微型動畫框架 JS)


var JS = {
  $: function(o) { return typeof o === 'string' ? document.getElementById(o) : o; },
  on: function(o, type, fn) {
    o.attachEvent ? o.attachEvent('on' + type, function() { fn.call(o); }) : o.addEventListener(type, fn, false);
    return JS.on;
  },
  move: function(who, attr, val, s, fn) {
    var fm = parseInt(who.style[attr]) || 0;
    clearInterval(who['timer_' + attr]);
    var iFx = (function(form, to, s) {
      return function() { return form += Math[form < to ? 'ceil' : 'floor']((to - form) * (s || 0.3)); };
    })(fm, val, s);
    who['timer_' + attr] = setInterval(function() {
      var v = iFx();
      who.style[attr] = v + 'px';
      if (v === val) { fn && fn.call(who); clearInterval(who['timer_' + attr]); }
    }, 18);
  }
};

JS.on(window, 'load', function() {
  var Q = JS.$('fx_topToolbar'); Q.style.top = '-74px';
  JS.on(JS.$('btn_offOn'), 'mouseover', function() { JS.move(Q, 'top', 0); });
  JS.on(Q, 'mouseout', function() { Q.outTimer = setTimeout(function() { JS.move(Q, 'top', -74); }, 10); });
  JS.on(Q, 'mouseover', function() { clearTimeout(this.outTimer); });
});

HTML 結構


<div id="fx_topToolbar">
  <div class="shell">
    <a href="#"><img src="1.gif" width="231" height="58" /></a>
    <a href="#"><img src="2.gif" width="231" height="58" /></a>
  </div>
  <div id="btn_offOn"><a href="#"></a></div>
</div>

關鍵技術點

  • 緩動算法:form += Math[form 形成指數衰減曲線。
  • 鏈式呼叫:JS.on(...)(...)(...) 透過回傳 JS.on 實現鏈式註冊多事件。
  • 定時器命名空間:who['timer_' + attr] 避免多屬性動畫衝突。
  • 延遲收合:mouseout 設定 10ms 延遲,mouseover 清除,防止閃爍。

現代化 CSS 版


#toolbar { position:fixed; top:0; left:0; right:0; height:92px; transform:translateY(-74px); transition:transform 0.3s ease; z-index:999; }
#toolbar:hover { transform:translateY(0); }
#btn_offOn { position:absolute; bottom:-8px; left:20px; /* 標籤樣式 */ }

零 JS、效能最佳、自動處理動畫中斷、支援觸控裝置(:hover 在行動端需配合 ontouchstart)。

copyright © 萬盛學電腦網 all rights reserved