頁面任意位置左鍵點擊,在滑鼠位置彈出自定義菜單(實為定位 DIV 內嵌表格),再次點擊或點擊菜單外關閉。純原生 JS 實現,無依賴,適合學習事件座標與動態定位。
<table cellpadding="5" id="itemopen" class="box" style="display:none">
<tr><td bgcolor="#0066cc">網站導航:</td></tr>
<tr><td><a href="/">AJAX實例</a></td></tr>
<tr><td><a href="/jscss/">jQuery相關</a></td></tr>
<tr><td><a href="/jscss/">ExtJS演示</a></td></tr>
</table>
菜單本質是隱藏的 table,樣式類 .box 設置 position:absolute、背景色。
document.onclick = popUp;
function popUp() {
newX = window.event.x + document.body.scrollLeft;
newY = window.event.y + document.body.scrollTop;
menu = document.all.itemopen; // 獲取菜單元素
if (menu.style.display == "") {
menu.style.display = "none";
} else {
menu.style.display = "";
}
menu.style.pixelLeft = newX - 50;
menu.style.pixelTop = newY - 50;
}
window.event(IE 模式),現代瀏覽器應用 event 參數或 e.clientX。clientX + scrollLeft 獲取頁面絕對座標。style.pixelLeft/pixelTop 是 IE 私有屬性,標準寫法 style.left = newX + 'px'。display 空字符串(顯示)與 none 切換。-50px 使菜單中心對準滑鼠點擊點。document.addEventListener('click', function(e) {
const menu = document.getElementById('itemopen');
const isVisible = menu.style.display !== 'none';
if (isVisible && !menu.contains(e.target)) {
menu.style.display = 'none';
return;
}
menu.style.display = 'block';
menu.style.left = e.clientX + window.scrollX - 50 + 'px';
menu.style.top = e.clientY + window.scrollY - 50 + 'px';
});
改進點:addEventListener、標準座標 API、contains() 判斷點擊是否在菜單外、ES6 語法。
contextmenu 事件,e.preventDefault() 禁用默認菜單。ul/li,滑鼠進入顯示子級。Tab/Enter/Esc 支持無障礙訪問。