--- title: GlobalEventHandlers.oncontextmenu slug: Web/API/GlobalEventHandlers/oncontextmenu tags: - API - Event Handler - GlobalEventHandlers - HTML DOM - Property - Reference ---
oncontextmenu
是用来设置或获取全局事件({{domxref("GlobalEventHandlers")}})中 上下文菜单事件({{event("contextmenu")}}) 的处理函数({{domxref("EventHandler")}})。
当在窗口上单击鼠标右键时,通常会触发 contextmenu
事件。 除非阻止默认行为,否则浏览器上下文菜单将被激活。
target.oncontextmenu = functionRef;
functionRef
是一个函数名 或者是一个 函数表达式。 该函数接收 {{domxref("Event")}} 作为唯一参数。
一次只能将一个 oncontextmenu
处理函数分配给一个对象。 你可能更喜欢使用 {{domxref("EventTarget.addEventListener()")}} 作为替代,
因为这种方式更加灵活。
右键单击通常会显示上下文菜单,但以下片段中将演示如何阻止在浏览器窗口(window)中显示上下文菜单。
<p>Try opening the context menu. Is it disabled?<p>
window.oncontextmenu = (e) => { e.preventDefault(); }
{{EmbedLiveSample("Disabling_context_menus")}}
此示例中,单击右键打开上下文菜单时将会暂停旋转动画。
<div class="shape">Spinning</div> <p class="note" hidden>Click to unpause.</p>
@keyframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; display: flex; align-items: center; justify-content: center; animation: spin 18s linear infinite; background: lightsalmon; border-radius: 42%; margin: 1em; } .paused { background-color: #ddd; } .paused .shape { animation-play-state: paused; }
const body = document.querySelector('body'); const note = document.querySelector('.note'); function pause(e) { body.classList.add('paused'); note.removeAttribute('hidden'); } function play(e) { body.classList.remove('paused'); note.setAttribute('hidden', ''); } window.oncontextmenu = pause; window.onpointerdown = play;
{{EmbedLiveSample("Pausing_an_animation", 700, 200)}}
规范 | 状态 | 备注 |
---|---|---|
{{SpecName('HTML WHATWG','webappapis.html#handler-oncontextmenu','oncontextmenu')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.GlobalEventHandlers.oncontextmenu")}}
除非阻止默认行为,否则右键单击将激活浏览器上下文菜单。但是, IE8 有一个 bug,如果定义了 contextmenu
处理函数,不会激活上下文菜单。