禁用特定元素的移动长按上下文菜单

Disable mobile longpress context menu on specific elements

本文关键字:上下文 菜单 移动 元素      更新时间:2023-09-26

我有一个带有各种控件的图像库。其中一个控件是一个基本的删除功能,要删除,请单击并按住约1秒钟以获得确认,询问您是否要删除。一切都很好,只是在移动设备上,它经常会弹出"将图像另存为"菜单,在执行预定操作之前必须关闭该菜单。

我读过各种修复程序,但它们似乎都不适用于我的Galaxy S5上当前版本的Chrome手机,我能找到的最新答案是2013年的。

我发现有人说上下文菜单是它自己的功能,所以我尝试了这样的东西:

    window.oncontextmenu = function(event) {
        event.preventDefault();
        event.stopPropagation();
        return false;
    };

但这并没有阻止上下文菜单显示在我的S5上。正如我所说,我希望找到一个解决方案,防止它出现在某些项目上,而不是整个窗口。

感谢Tasos的回答

document.getElementById('yourElement').oncontextmenu = function(event) {
    event.preventDefault();
    event.stopPropagation(); // not necessary in my case, could leave in case stopImmediateProp isn't available? 
    event.stopImmediatePropagation();
    return false;
};

我(重新)在这里发布答案,因为一开始,我还没有在问题中看到它:)

所以只要使用这个代码,使用stopImmediatePropagation:

document.getElementById('yourElement').oncontextmenu = function(event) {
    event.preventDefault();
    event.stopPropagation(); // not necessary in my case, could leave in case stopImmediateProp isn't available? 
    event.stopImmediatePropagation();
    return false;
};