Element:toggleAttribute() 方法
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Element
接口的 toggleAttribute()
方法翻转给定元素的某个布尔属性的状态(如果属性存在则移除,属性不存在则添加)。
语法
js
toggleAttribute(name)
toggleAttribute(name, force)
参数
返回值
如果属性的名称(name
)最终存在,则返回 true
,否则返回 false
。
异常
InvalidCharacterError
DOMException
-
指定属性名称(
name
)包含一个或多个在属性名称中无效的字符。
示例
在下面的例子中,toggleAttribute()
被用于切换 <input>
的 disabled
属性。
HTML
html
<input value="文本" /> <button>toggleAttribute("disabled")</button>
JavaScript
js
const button = document.querySelector("button");
const input = document.querySelector("input");
button.addEventListener("click", () => {
input.toggleAttribute("disabled");
});
结果
规范
Specification |
---|
DOM # ref-for-dom-element-toggleattribute① |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
toggleAttribute |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.