Movatterモバイル変換


[0]ホーム

URL:


  1. 給開發者的 Web 技術文件
  2. Web API
  3. Event
  4. Event.preventDefault()

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in EnglishAlways switch to English

Event.preventDefault()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.

概要

如果事件可以被取消,就取消事件(即取消事件的預設行為)。但不會影響事件的傳遞,事件仍會繼續傳遞。

語法

js
event.preventDefault();

範例

Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening:

html
<!doctype html><html>  <head>    <title>preventDefault example</title>  </head>  <body>    <p>Please click on the checkbox control.</p>    <form>      <label for="id-checkbox">Checkbox</label>      <input type="checkbox" />    </form>    <script>      document.querySelector("#id-checkbox").addEventListener(        "click",        function (event) {          alert("preventDefault will stop you from checking this checkbox!");          event.preventDefault();        },        false,      );    </script>  </body></html>

You can seepreventDefault in actionhere.

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault().

<!DOCTYPE html><html><head><title>preventDefault example</title><script>
function Init() {  var myTextbox = document.getElementById("my-textbox");  myTextbox.addEventListener("keypress", checkName, false);}function checkName(evt) {  var charCode = evt.charCode;  if (charCode != 0) {    if (charCode < 97 || charCode > 122) {      evt.preventDefault();      alert(        "Please use lowercase letters only." +          "\n" +          "charCode: " +          charCode +          "\n",      );    }  }}
</script></head><body onload="Init ()">    <p>Please enter your name using lowercase letters only.</p>    <form>        <input type="text" />    </form></body></html>

Here is the result of the preceding code:

備註

CallingpreventDefault during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

備註:As of Gecko 6.0, callingpreventDefault() causes theevent.defaultPrevented property's value to becometrue.

你可以查看Event.cancelable 屬性來檢查事件是否能夠被取消。對一個不能被取消的事件呼叫preventDefault() 方法是沒有任何效果的。

preventDefault() 方法不會停止事件傳遞。若要停止事件繼續傳遞,可以使用Event.stopPropagation() 方法。

規範

Specification
DOM
# ref-for-dom-event-preventdefault③

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp