一個基於原生 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 模塊化導出。transition: transform 0.3s ease-out,JS 僅切換類名或設置 transform。onmouseover。<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>