事件
接口的
preventDefault()
方法告诉
用户代理
若事件未获得明确处理,就不应该像通常那样接受其默认动作。
事件继续照常传播,除非某一事件监听器调用
stopPropagation()
or
stopImmediatePropagation()
, either of which terminates propagation at once.
如下所述,调用
preventDefault()
对于不可取消事件,如某一分派凭借
EventTarget.dispatchEvent()
,不指定
cancelable: true
不起作用。
event.preventDefault();
切换复选框是点击复选框的默认动作。此范例演示如何阻止这种情况的发生:
document.querySelector("#id-checkbox").addEventListener("click", function(event) {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
event.preventDefault();
}, false);
<p>Please click on the checkbox control.</p> <form> <label for="id-checkbox">Checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div>
The following example demonstrates how invalid text input can be stopped from reaching the input field with
preventDefault()
. Nowadays, you should usually use
native HTML form validation
代替。
Here's the form:
<div class="container">
<p>Please enter your name using lowercase letters only.</p>
<form>
<input type="text" id="my-textbox">
</form>
</div>
We use a little bit of CSS for the warning box we'll draw when the user presses an invalid key:
.warning {
border: 2px solid #f39389;
border-radius: 2px;
padding: 10px;
position: absolute;
background-color: #fbd8d4;
color: #3b3c40;
}
And here's the JavaScript code that does the job. First, listen for
keypress
事件:
var myTextbox = document.getElementById('my-textbox');
myTextbox.addEventListener('keypress', checkName, false);
checkName()
function, which looks at the pressed key and decides whether to allow it:
function checkName(evt) {
var charCode = evt.charCode;
if (charCode != 0) {
if (charCode < 97 || charCode > 122) {
evt.preventDefault();
displayWarning(
"Please use lowercase letters only."
+ "\n" + "charCode: " + charCode + "\n"
);
}
}
}
displayWarning()
function presents a notification of a problem. It's not an elegant function but does the job for the purposes of this example:
var warningTimeout;
var warningBox = document.createElement("div");
warningBox.className = "warning";
function displayWarning(msg) {
warningBox.innerHTML = msg;
if (document.body.contains(warningBox)) {
window.clearTimeout(warningTimeout);
} else {
// insert warningBox after myTextbox
myTextbox.parentNode.insertBefore(warningBox, myTextbox.nextSibling);
}
warningTimeout = window.setTimeout(function() {
warningBox.parentNode.removeChild(warningBox);
warningTimeout = -1;
}, 2000);
}
调用
preventDefault()
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.
可以使用
Event.cancelable
to check if the event is cancelable. Calling
preventDefault()
for a non-cancelable event has no effect.
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
在该规范中的 Event.preventDefault() 定义。 |
实时标准 | |
|
DOM (文档对象模型) 2 级事件规范
在该规范中的 Event.preventDefault() 定义。 |
过时 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
preventDefault
|
Chrome 1 | Edge 12 | Firefox 1 | IE 9 | Opera 7 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
事件
composedPath
initEvent
msConvertURL()
preventDefault
stopImmediatePropagation
stopPropagation
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument