Event.cancelable - Web APIs 编辑

The cancelable read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. If the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring.

Event listeners that handle multiple kinds of events may want to check cancelable before invoking their preventDefault() methods.

Most browser-native events that can be canceled are the ones that result from the user interacting with the page. Canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively.

Custom events created by other JavaScript code control if they can be canceled when they are created.

Syntax

bool = event.cancelable;

Value

The result is a Boolean, which is true if the event can be canceled.

Example

For example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called — any following wheel events cannot be canceled.

function preventScrollWheel(event) {
  if (typeof event.cancelable !== 'boolean' || event.cancelable) {
    // The event can be canceled, so we do so.
    event.preventDefault();
  } else {
    // The event cannot be canceled, so it is not safe
    // to call preventDefault() on it.
    console.warn(`The following event couldn't be canceled:`);
    console.dir(event);
  }
}

document.addEventListener('wheel', preventScrollWheel);

Notes

Whether an event can be canceled or not is something that's determined when that event is initialized.

To cancel an event, call the preventDefault() method on the event. This keeps the implementation from executing the default action that is associated with the event.

Specifications

SpecificationStatusComment
DOM
The definition of 'Event.cancelable' in that specification.
Living Standard
Document Object Model (DOM) Level 2 Events Specification
The definition of 'Event.cancelable' in that specification.
ObsoleteInitial definition.

Browser compatibility

BCD tables only load in the browser

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

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

发布评论

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

词条统计

浏览:76 次

字数:4257

最后编辑:6 年前

编辑次数:0 次

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