萬盛學電腦網

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

JS 特效:炫酷滑動菜單效果完整實現

效果概覽

一個基於原生 JavaScript 的下拉/滑動導航菜單,具有平滑的位置/尺寸動畫過渡、懸停展開、點擊導航功能。雖然代碼風格較早期(ES3、大量 eval、document.write),但其動畫插值邏輯值得參考。

核心架構

function CoolMenuControl() {
  // 狀態屬性
  this.lastScrollX = 0; this.lastScrollY = 0;
  this.lastScrollW = 0; this.lastScrollH = 0;
  this.menuarray = [];  // 菜單項數據
  this.speed = 0.3;     // 動畫緩動係數 (0-1)

  // 菜單項構造器
  function MenuItem(type, value, url, target) {
    this.type = type;     // 0:主標題 1:子標題 2:葉子項
    this.value = value;   // 顯示文本
    this.url = url;       // 鏈接
    this.target = target; // 目標窗口
  }

  // 插入菜單項
  this.insertmenu = function(type, value, url, target) {
    this.menuarray.push(new MenuItem(type, value, url, target));
  };

  // 初始化渲染
  this.init = function(name, borderColor, bgColor, speed, alpha) { ... };
  // 動畫循環
  this.scrollback = function() { ... };
  // 懸停觸發目標位置計算
  this.doOver = function() { ... };
  // 絕對定位計算
  this.posXY = function(obj) { ... };
  // 點擊跳轉
  this.doClick = function() { ... };
}

關鍵動畫邏輯:插值緩動

this.scrollback = function() {
  // 目標位置/尺寸
  const diffX = this.td_X - 3;
  const diffY = this.td_Y - 5;
  const diffW = this.td_W;
  const diffH = this.td_H;

  // 線性插值:當前 += (目標 - 當前) * speed
  const percentX = this.speed * (diffX - this.lastScrollX);
  const percentY = this.speed * (diffY - this.lastScrollY);
  const percentW = this.speed * (diffW - this.lastScrollW);
  const percentH = this.speed * (diffH - this.lastScrollH);

  // 整數像素修正
  this.lastScrollX += Math[percentX > 0 ? 'ceil' : 'floor'](percentX);
  this.lastScrollY += Math[percentY > 0 ? 'ceil' : 'floor'](percentY);
  this.lastScrollW += Math[percentW > 0 ? 'ceil' : 'floor'](percentW);
  this.lastScrollH += Math[percentH > 0 ? 'ceil' : 'floor'](percentH);

  // 應用到懸浮提示層
  eval(this.hk_name).style.pixelLeft = this.lastScrollX;
  eval(this.hk_name).style.pixelTop = this.lastScrollY;
  eval(this.hktable_name).style.pixelWidth = this.lastScrollW;
  eval(this.hktable_name).style.pixelHeight = this.lastScrollH;
};

此為經典的「緩動動畫」模型:current += (target - current) * easing,現代可用 requestAnimationFrame + CSS transition 替代。

現代化重構建議

  • 移除 eval、document.write,改用 document.createElement、appendChild。
  • 用 class 封裝,ES6 模塊化導出。
  • 動畫改用 CSS transition: transform 0.3s ease-out,JS 僅切換類名或設置 transform。
  • 事件委託綁定在容器上,避免大量內聯 onmouseover。
  • 菜單數據結構改為 JSON,渲染函數遍歷生成 DOM。

使用示例

<script src="coolmenu.js"></script>
<script>
var menu = new CoolMenuControl();
menu.insertmenu("0", "產品中心", "", "_self");      // 主標題
menu.insertmenu("1", "Web 開發", "web.html", "_blank"); // 子標題
menu.insertmenu("2", "Vue 教程", "vue.html", "_blank"); // 葉子項
menu.insertmenu("2", "React 教程", "react.html", "_blank");
menu.init("menu1", "#006699", "#f0f0f0", 0.3, 80); // 名稱、邊框色、背景色、速度、透明度
</script>
copyright © 萬盛學電腦網 all rights reserved