GlobalEventHandlers.oncontextmenu - Web APIs 编辑

The oncontextmenu property of the GlobalEventHandlers mixin is an EventHandler that processes contextmenu events.

The contextmenu event typically fires when the right mouse button is clicked on the window. Unless the default behavior is prevented, the browser context menu will activate.

Syntax

target.oncontextmenu = functionRef;

Value

functionRef is a function name or a function expression. The function receives an Event object as its sole argument.

Only one oncontextmenu handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible.

Examples

Disabling context menus

This snippet prevents context menus from opening in the window. The context menu typically appears upon a right click.

HTML

<p>Try opening the context menu. Is it disabled?<p>

JavaScript

window.oncontextmenu = (e) => {
  e.preventDefault();
}

Result

Pausing an animation

This example pauses a spinning shape whenever you open the context menu.

HTML

<div class="shape">Spinning</div>
<p class="note" hidden>Click to unpause.</p>

CSS

@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;
}

JavaScript

function pause(e) {
  body.classList.add('paused');
  note.removeAttribute('hidden');
}

function play(e) {
  body.classList.remove('paused');
  note.setAttribute('hidden', '');
}

const body = document.querySelector('body');
const note = document.querySelector('.note');

window.oncontextmenu = pause;
window.onpointerdown = play;

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'oncontextmenu' in that specification.
Living Standard 

Browser compatibility

BCD tables only load in the browser

Unless the default behavior is prevented, the browser context menu will activate upon right-click. However, IE8 has a bug with this and will not activate the context menu if a contextmenu event handler is defined.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:109 次

字数:5366

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文