如何使用 javascript 覆盖 Web 中默认的右键单击行为

问题描述 投票:0回答:1

在 Web 应用程序中,右键单击时,通常会显示上下文菜单。我想覆盖此默认行为并显示我的自定义菜单。我编写了以下代码。然而,我面临的问题是默认上下文菜单和我的自定义上下文菜单都被显示。我只想显示我的自定义上下文菜单,而不是默认菜单。

document.addEventListener("DOMContentLoaded", function () {
    window.showContextMenu = (id, name, width, height, locationX, locationY) => {
        var contextMenu = document.getElementById("contextMenu");
        contextMenu.style.position = "absolute";
        contextMenu.style.left = locationX + "px";
        contextMenu.style.top = locationY + "px";
        contextMenu.style.display = "block";

        contextMenu.innerHTML = `
            <ul>
                <li>Id: ${id}</li>
                <li>Name: ${name}</li>
                <li>Width: ${width}</li>
                <li>Height: ${height}</li>
                <li>LocationX: ${locationX}</li>
                <li>LocationY: ${locationY}</li>
            </ul>
        `;

        // Create the close button element
        const closeButton = document.createElement("button");
        closeButton.textContent = "Close";
        closeButton.id = "closeButton";

        // Add a click event listener to the close button
        closeButton.addEventListener("click", function () {
            contextMenu.style.display = "none";
        });

        // Append the close button to the context menu
        contextMenu.appendChild(closeButton);
    };


    const contextMenu = document.getElementById("contextMenu");
    contextMenu.addEventListener("contextmenu", function (e) {
        e.preventDefault();
    });
});



const contextMenu = document.getElementById("contextMenu");
contextMenu.addEventListener("contextmenu", function (e) {
    e.preventDefault();
});

我尝试了 e.preventDefault();但它没有按预期工作。

javascript contextmenu
1个回答
0
投票

问题在于您仅阻止自定义上下文菜单上的默认行为,而不是阻止右键单击的整个文档或目标元素上的默认行为。 为了防止显示默认上下文菜单,您应该将 contextmenu 事件侦听器附加到整个文档或特定目标元素,并在那里调用 e.preventDefault() 。确保在所需元素上右键单击之前添加侦听器。

这是一个建议的实现:

document.addEventListener("DOMContentLoaded", function () {
    document.addEventListener("contextmenu", function (e) {
        e.preventDefault();  // Prevent default context menu from showing up
        showContextMenu();
    });
});

function showContextMenu() {
    var contextMenu = document.getElementById("contextMenu");
    
    // ... 

    contextMenu.style.display = "block";
}

© www.soinside.com 2019 - 2024. All rights reserved.