如何在触控屏上捕获右键菜单事件,同时忽略鼠标按下事件

前端开发 2026-07-08

我有这段代码,可以检测 touchstartonmousedownoncontextmenu 事件:

            var h1 = document.querySelector("h1");
            h1.ontouchstart=function(){h1.innerText='touchstart';return true;};
            h1.onmousedown=function(){h1.innerText='mousedown';return false;};
            h1.oncontextmenu=function(){h1.innerText='contextmenu';return false;};
<!DOCTYPE html>
<html>
    <body>
        <h1>TEXT</h1>
    </body>
</html>

在使用触控屏时,这会报告 touchstart 以及 mousedown 事件(针对同一个触控),但如果我通过在ontouchstart中返回 false 来禁用它:

var h1 = document.querySelector("h1");
h1.ontouchstart=function(){h1.innerText='touchstart';return false;};
h1.onmousedown=function(){h1.innerText='mousedown';return false;};
h1.oncontextmenu=function(){h1.innerText='contextmenu';return false;};
<!DOCTYPE html>
<html>
    <body>
        <h1>TEXT</h1>
    </body>
</html>

它也会停止记录 contextmenu(长按)事件。
有没有办法只停止 mouse* 事件,或以某种方式检查鼠标事件是否是由触摸事件引起的?仅仅检查是否存在触控屏并不足够,因为笔记本电脑也可能同时具备触控屏和触控板/鼠标

解决方案

因为 contextmenu 事件在 touchstart 之后、在 touchend 之前被触发,根据W3C标准,取消任何 touch* 事件将阻止生成的模拟 mouse* 事件,因此你可以直接取消 touchend(也许还可以取消 touchcancel)事件。

var h1 = document.querySelector("h1");
h1.ontouchstart=function(){h1.innerText='touchstart';return true;};
h1.ontouchend=function(){return false;};
h1.ontouchcancel=function(){return false;};
h1.onmousedown=function(){h1.innerText='mousedown';return false;};
h1.oncontextmenu=function(){h1.innerText='contextmenu';return false;};
<!DOCTYPE html>
<html>
    <body>
        <h1>TEXT</h1>
    </body>
</html>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章