blob: 33e3e320f125e438004814f04718f3fa635dec03 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
---
title: DOMTokenList.toggle()
slug: Web/API/DOMTokenList/toggle
tags:
- .toggle()
- DOMTokenList.toggle()
- classList
translation_of: Web/API/DOMTokenList/toggle
---
<p>{{APIRef("DOM")}}</p>
<p>{{domxref("DOMTokenList")}} 接口的 <code><strong>toggle()</strong></code> 方法从列表中删除一个给定的<em>标记 </em>并返回 <code>false</code> 。 如果<em>标记 </em>不存在,则添加并且函数返回 <code>true</code>。</p>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">tokenList.toggle(token, force);</pre>
<h3 id="参数列表">参数列表</h3>
<dl>
<dt>token</dt>
<dd>标记列表中你想探查并切换的 {{domxref("DOMString")}} .</dd>
<dt>force {{optional_inline}}</dt>
<dd>一个{{domxref("Boolean")}} 值, 设置后会将方法变成单向操作. 如设置为<code>false</code>, 则会删除标记列表中匹配的给定标记,且不会再度添加. 如设置为 <code>true</code>, 则将在标记列表中添加给定标记,且不会再度删除。</dd>
</dl>
<h3 id="返回值">返回值</h3>
<p>该方法返回一个{{domxref("Boolean")}}值 — 如给定标记不存在于列表中返回<code>false</code> , 标记存在则返回<code>true</code> 。</p>
<h2 id="Examples">Examples</h2>
<p>In the following example we retrieve the list of classes set on a {{htmlelement("span")}} element as a <code>DOMTokenList</code> using {{domxref("Element.classList")}}. We then replace a token in the list, and write the list into the <code><span></code>'s {{domxref("Node.textContent")}}.</p>
<p>First, the HTML:</p>
<pre class="brush: html"><span class="a b">classList is 'a b'</span></pre>
<p>Now the JavaScript:</p>
<pre class="brush: js">var span = document.querySelector("span");
var classes = span.classList;
span.onclick = function() {
var result = classes.toggle("c");
if(result) {
span.textContent = "'c' added; classList is now '" + classes + "'.";
} else {
span.textContent = "'c' removed; classList is now '" + classes + "'.";
}
}
</pre>
<p>The output looks like this:</p>
<p>{{ EmbedLiveSample('Examples', '100%', 60) }}</p>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('DOM WHATWG','#dom-domtokenlist-toggle','toggle()')}}</td>
<td>{{Spec2('DOM WHATWG')}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
{{Compat("api.DOMTokenList.toggle")}}
|