萬盛學電腦網

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

JS 經典特效:下拉透明菜單實現原理解析

效果描述

頂部導航欄,鼠標懸停主菜單項,半透明下拉子菜單以「百葉窗/卷簾」動畫展開(clip: rect() 裁剪動畫),支持多級子菜單、延時隱藏、鍵盤導航。

核心技術點

1. 裁剪動畫


// 核心動畫函數:通過 clip 裁剪實現展開/收起
function swipe(el, dir, steps = 4, msec = 25) {
    // dir: 2=向上, 8=向下, 6=向左, 4=向右
    if (el.swipeTimer) clearTimeout(el.swipeTimer);
    
    // 記錄原始尺寸
    if (!el.swipeCounter) {
        el.orgLeft = el.offsetLeft;
        el.orgTop = el.offsetTop;
        el.orgWidth = el.offsetWidth;
        el.orgHeight = el.offsetHeight;
    }
    el.swipeCounter = steps;
    el.style.clip = 'rect(0,0,0,0)'; // 完全隱藏
    el.style.visibility = 'visible';
    
    // 遞歸動畫
    function repeat() {
        const step = 1 - el.swipeCounter / steps; // 0 → 1
        let clip;
        switch(dir) {
            case 8: // 向下展開(最常用)
                clip = `rect(0, ${el.orgWidth}px, ${el.orgHeight * step}px, 0)`;
                el.style.top = el.orgTop + el.orgHeight * (1 - step) + 'px';
                break;
            // ... 其他方向
        }
        el.style.clip = clip;
        el.swipeCounter--;
        if (el.swipeCounter >= 0) {
            el.swipeTimer = setTimeout(repeat, msec);
        } else {
            el.style.clip = 'rect(auto, auto, auto, auto)'; // 恢復
        }
    }
    repeat();
}

原理:clip: rect(top, right, bottom, left) 定義可視矩形。通過逐幀增加 bottom 值(向下展開)或調整 top(向上展開),產生「從無到有」的動畫。此為 CSS clip-path/transform 普及前的主流方案。

2. 菜單數據結構


// 主菜單項
function mMenu(caption, command, target, img, sizex, sizey, pos) {
    this.items = [];      // 子菜單項
    this.caption = caption; // 顯示文本
    this.command = command; // 鏈接/JS代碼
    this.target = target;   // _blank/_self
    this.id = mMenuRegister(this); // 註冊全局索引
}

// 子菜單項
function mMenuItem(caption, command, target, isline, statustxt, level, img, sizex, sizey, pos) {
    this.items = [];      // 支持多級嵌套
    this.level = level;   // 層級
    this.hasc = ++mnumberofsub; // 子菜單索引
}

3. 顯示/隱藏狀態機


// 顯示主菜單下拉
function mmenushow(menuid, pid) {
    menuid.style.filter = 'Alpha(Opacity=80)'; // IE 濾鏡透明度
    menuid.style.left = mposflag.offsetLeft + pid.offsetLeft + mmenuadjust;
    menuid.style.top = mposflag.offsetTop + pid.offsetTop + pid.offsetHeight + mmenuadjustV;
    swipe(menuid, 8); // 向下展開動畫
    misShow = true;
}

// 隱藏所有(含子菜單)
function mallhide() {
    // 遍歷所有主菜單
    mmenus.forEach((menu, i) => {
        mnochange(document.all['mMenu'+i]); // 恢復樣式
        mmenuhide(document.all['mmenudiv'+i]);
    });
    // 遍歷所有子菜單
    for (let i=1; i<=mnumberofsub; i++) {
        msubmenuhide(document.all['msubmenudiv'+i]);
        mnochange(document.all['mp'+i]);
        document.all['mitem'+i].style.color = mfontcolor;
    }
}

// 延時隱藏(鼠標移出後 500ms)
function mpopOut() { mpopTimer = setTimeout(mallhide, 500); }

4. IE 濾鏡與透明度


// IE 專有濾鏡(IE4-9)
el.style.filter = 'Alpha(Opacity=80)'; // 80% 不透明度
// 現代瀏覽器
el.style.opacity = '0.8';
// 兼容寫法
el.style.cssText = 'opacity:0.8; filter:Alpha(Opacity=80);';

5. 事件綁定模式(老式)


// 文檔級事件(模擬委託)
document.onmousedown = engage;   // 按下:判斷是否點在菜單項上
document.onmousemove = dragIt;   // 移動:拖拽選中項(本例未用到拖拽,殘留代碼)
document.onmouseup = release;    // 釋放

// engage: 設置 selectedObj = 目標元素,記錄 offsetX/Y
// dragIt: 若 selectedObj 存在,調用 shiftTo 移動(本例為拖拽高亮塊?代碼截斷)
// release: 清空 selectedObj

代碼截斷遺憾

原文代碼在 shiftTo 函數中斷,無法看到完整的子菜單定位、多級展開、鍵盤支持邏輯。但可見其架構:

  • 全局數組管理所有菜單實例
  • 靜態配置對象定義樣式常量(顏色、尺寸、字體)
  • clip 動畫引擎
  • IE 濾鏡透明度
  • 文檔級事件循環

現代重寫方案(CSS + 少量 JS)


/* CSS 版:零 JS 動畫,純 CSS 過渡 */
.nav { display: flex; }
.nav-item { position: relative; }
.nav-submenu {
    position: absolute;
    top: 100%; left: 0;
    min-width: 180px;
    background: rgba(255,255,255,0.95); /* 半透明 */
    backdrop-filter: blur(8px);         /* 毛玻璃 */
    border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
    opacity: 0;
    visibility: hidden;
    transform: translateY(-10px);
    transition: all 0.2s ease;
    pointer-events: none;
}
.nav-item:hover .nav-submenu,
.nav-item:focus-within .nav-submenu {
    opacity: 1;
    visibility: visible;
    transform: translateY(0);
    pointer-events: auto;
}

/* 多級子菜單 */
.nav-submenu .nav-submenu {
    top: 0; left: 100%; /* 右側展開 */
    margin-left: 8px;
}

// JS 僅處理:鍵盤導航、觸摸設備 click 切換、延時隱藏邏輯
const NAV = document.querySelector('.nav');
let hideTimer;
NAV.addEventListener('mouseover', e => {
    clearTimeout(hideTimer);
    e.target.closest('.nav-item')?.classList.add('hover');
});
NAV.addEventListener('mouseout', e => {
    hideTimer = setTimeout(() => {
        NAV.querySelectorAll('.nav-item.hover').forEach(el => el.classList.remove('hover'));
    }, 300);
});
// 鍵盤支持
NAV.addEventListener('keydown', e => { /* Tab/Enter/Escape/Arrow keys */ });

總結

下拉透明菜單展示了 DHTML 時代的頂尖技術:clip 裁剪動畫、IE 濾鏡透明度、文檔級事件循環、多級菜單數據結構、延時隱藏狀態機。現代開發中,**CSS opacity/visibility/transform + transition 完全替代 JS 動畫**,JS 僅處理交互邏輯(鍵盤、觸摸、延時),代碼量減少 90%,性能體驗大幅提升。理解歷史實現有助於欣賞現代 CSS 的威力。

copyright © 萬盛學電腦網 all rights reserved