aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/html/element/input/radio/index.html
blob: 0ffa30a831305587b7a3e9a00dd14119daaa16c8 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
---
title: <input type="radio">
slug: Web/HTML/Element/Input/radio
tags:
  - Choosing Options
  - Element
  - Form Options
  - HTML
translation_of: Web/HTML/Element/input/radio
---
<p>{{HTMLRef}}</p>

<p>{{htmlelement("input")}} 的 <strong><code>radio</code></strong> 类型元素默认渲染为小型圆圈图表,填充即为激活,类似于之前描述额复选框(checkbox)类型。单选按钮允许你选择单一的值来提交表单。</p>

<p>{{EmbedInteractiveExample("pages/tabbed/input-radio.html", "tabbed-standard")}}</p>

<p>它们被称为单选按钮,因为它们的外观和操作方式与老式无线电上的按钮类似,如下图所示。</p>

<p><img alt="Shows what radio buttons looked like in the olden days." src="https://mdn.mozillademos.org/files/15610/old-radio.jpg" title="Photo of an old-time radio"></p>

<div class="note">
<p><span style="font-size: 14px;"><strong>注意:</strong></span><a href="/en-US/docs/Web/HTML/Element/input/checkbox">复选框</a>类似于单选按钮,但是有个重要的区别 -- 单选按钮为选择其中一项而设计,然而复选框允许你开启或关闭单个值。每个独立的单选按钮大致上是 {{domxref("Boolean")}} 控件 --  是或不是。</p>
</div>

<table class="properties">
 <tbody>
  <tr>
   <td><strong>{{anch("Value")}}</strong></td>
   <td>A {{domxref("DOMString")}} representing the value of the radio button.</td>
  </tr>
  <tr>
   <td><strong>Events</strong></td>
   <td>{{event("change")}} and {{event("input")}}</td>
  </tr>
  <tr>
   <td><strong>Supported common attributes</strong></td>
   <td>{{htmlattrxref("checked", "input")}}</td>
  </tr>
  <tr>
   <td><strong>IDL attributes</strong></td>
   <td><code>checked</code> and <code>value</code></td>
  </tr>
  <tr>
   <td><strong>Methods</strong></td>
   <td>{{domxref("HTMLInputElement.select", "select()")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="值"></h2>

<p>A {{domxref("DOMString")}} 表示单选按钮的值。它永远不会在客户端看到,但是在服务器上,这就是使用单选按钮 <code>name</code> 提交的数据的 <code>value</code>。查看以下示例:</p>

<h3 id="定义一个单选按钮组节">定义一个单选按钮组<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/Input/radio$edit#Defining_a_radio_group"></a></h3>

<p>一个单选按钮组由具有相同 {{htmlattrxref("name", "input")}}属性的单选按钮组成。 一旦单选按钮组被建立,选择那按钮组的任何单选按钮将会自动取消同组当前选择的任何按钮。</p>

<p>你可以在一个页面上创建任何你喜欢的单选按钮组,只要每一组都有一个独特的 <code>name</code>属性。</p>

<p>举个例子,如果你需要在表单中询问用户的首选联系方式,你可以创建三个 <code>name</code> 属性都为 <code>contact</code> 的单选按钮,不过一个按钮的 {{htmlattrxref("value", "input")}}属性为 <code>email</code> ,另一个的<code>value</code> 属性为 <code>phone</code>,还有一个的<code>value</code> 属性为 <code>mail</code>。用户不会看见 <code>value</code> 属性或 <code>name</code> 属性(除非你故意用代码显示它们)。</p>

<p>最终的 HTML 可能看起来像这样:</p>

<pre class="brush: html notranslate">&lt;form&gt;
  &lt;p&gt;Please select your preferred contact method:&lt;/p&gt;
  &lt;div&gt;
    &lt;input type="radio" id="contactChoice1"
     name="contact" value="email"&gt;
    &lt;label for="contactChoice1"&gt;Email&lt;/label&gt;

    &lt;input type="radio" id="contactChoice2"
     name="contact" value="phone"&gt;
    &lt;label for="contactChoice2"&gt;Phone&lt;/label&gt;

    &lt;input type="radio" id="contactChoice3"
     name="contact" value="mail"&gt;
    &lt;label for="contactChoice3"&gt;Mail&lt;/label&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
</pre>

<p>你可以在这里看到三个单选按钮,每个按钮的 <code>name</code> 属性都设置为 <code>contact</code> 并且都含有在单选按钮组中唯一的 <code>value</code> 属性。 每一个单选按钮也有一个给{{HTMLElement("label")}} 元素的 {{htmlattrxref("for", "label")}}属性使用的{{domxref("Element.id", "id")}},将 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">label</span></font> 元素和点选按钮关联。</p>

<p><em>译者注:你可以用 <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">label</span></font> 元素把 <code>input</code> 元素包裹起来,以减少 <code>id</code> 的使用。</em></p>

<p>你可以在这里查看这个例子:</p>

<p>{{EmbedLiveSample('Defining_a_radio_group', 600, 130)}}</p>

<h3 id="Data_representation_of_a_radio_group">Data representation of a radio group</h3>

<p>当上面的表单在提交时选择了一个单选框,表单的数据就包括了<code>contact=<em>value</em></code>一行。例如,若用户点击 "Phone "单选框,然后提交表单,提交的数据中将包括<code>contact=phone</code>一行。</p>

<p>如果你在 HTML 中忘记了 value 属性,那么提交的表单数据就会将该值分配到<code>on</code>上。在这种情况下,如果用户选中了 "Phone "选项并提交了表单,提交的表单数据将是<code>contact=on</code>,这并没有什么卵用。所以别忘了设置你的<code>value</code>属性!</p>

<p><strong>Note</strong>: 如果在提交表单时没有选择任何单选按钮,则提交的表格数据中根本不包括单选组,因为没有值要报告。</p>

<p>It's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the <code>checked</code> state. See {{anch("Selecting a radio button by default")}} below.</p>

<p>Let's add a little bit of code to our example so we can examine the data generated by this form. The HTML is revised to add a {{HTMLElement("pre")}} block to output the form data into:</p>

<pre class="brush: html notranslate">&lt;form&gt;
  &lt;p&gt;Please select your preferred contact method:&lt;/p&gt;
  &lt;div&gt;
    &lt;input type="radio" id="contactChoice1"
           name="contact" value="email"&gt;
    &lt;label for="contactChoice1"&gt;Email&lt;/label&gt;
    &lt;input type="radio" id="contactChoice2"
           name="contact" value="phone"&gt;
    &lt;label for="contactChoice2"&gt;Phone&lt;/label&gt;
    &lt;input type="radio" id="contactChoice3"
           name="contact" value="mail"&gt;
    &lt;label for="contactChoice3"&gt;Mail&lt;/label&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
&lt;pre id="log"&gt;
&lt;/pre&gt;</pre>

<p>Then we add some <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">JavaScript</a> to set up an event listener on the {{event("submit")}} event, which is sent when the user clicks the "Submit" button:</p>

<pre class="brush: js notranslate">var form = document.querySelector("form");
var log = document.querySelector("#log");

form.addEventListener("submit", function(event) {
  var data = new FormData(form);
  var output = "";
  for (const entry of data) {
    output = entry[0] + "=" + entry[1] + "\r";
  };
  log.innerText = output;
  event.preventDefault();
}, false);</pre>

<p>Try this example out and see how there's never more than one result for the <code>contact</code> group.</p>

<p>{{EmbedLiveSample("Data_representation_of_a_radio_group", 600, 130)}}</p>

<h2 id="Additional_attributes">Additional attributes</h2>

<p>In addition to the common attributes shared by all {{HTMLElement("input")}} elements, <code>radio</code>inputs support the following attributes:</p>

<table>
 <thead>
  <tr>
   <th scope="col">Attribute</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>{{anch("checked")}}</code></td>
   <td>A Boolean indicating whether or not this radio button is the currently-selected item in the group</td>
  </tr>
 </tbody>
</table>

<h3 id="htmlattrdefchecked">{{htmlattrdef("checked")}}</h3>

<p>A Boolean attribute which, if present, indicates that this radio button is the currently selected one in the group.</p>

<p>Unlike other browsers, Firefox by default <a href="https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing">persists the dynamic checked state</a> of an <code>&lt;input&gt;</code>across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.</p>

<h2 id="Using_radio_inputs">Using radio inputs</h2>

<p>We already covered the fundamentals of radio buttons above. Let's now look at the other common radio-button-related features and techniques you may need to know about.</p>

<h3 id="Selecting_a_radio_button_by_default">Selecting a radio button by default</h3>

<p>To make a radio button selected by default, you simply include <code>checked</code> attribute, as shown in this revised version of the previous example:</p>

<pre class="brush: html notranslate">&lt;form&gt;
  &lt;p&gt;Please select your preferred contact method:&lt;/p&gt;
  &lt;div&gt;
    &lt;input type="radio" id="contactChoice1"
     name="contact" value="email" checked&gt;
    &lt;label for="contactChoice1"&gt;Email&lt;/label&gt;

    &lt;input type="radio" id="contactChoice2"
     name="contact" value="phone"&gt;
    &lt;label for="contactChoice2"&gt;Phone&lt;/label&gt;

    &lt;input type="radio" id="contactChoice3"
     name="contact" value="mail"&gt;
    &lt;label for="contactChoice3"&gt;Mail&lt;/label&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;</pre>

<p>{{EmbedLiveSample('Selecting_a_radio_button_by_default', 600, 130)}}</p>

<p>In this case, the first radio button is now selected by default.</p>

<p><strong>Note</strong>: If you put the <code>checked</code> attribute on more than one radio button, later instances will override earlier ones; that is, the last <code>checked</code> radio button will be the one that is selected. This is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked.</p>

<h3 id="Providing_a_bigger_hit_area_for_your_radio_buttons">Providing a bigger hit area for your radio buttons</h3>

<p>In the above examples, you may have noticed that you can select a radio button by clicking on its associated {{htmlelement("label")}} element, as well as on the radio button itself. This is a really useful feature of HTML form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones.</p>

<p>Beyond accessibility, this is another good reason to properly set up <code>&lt;label&gt;</code> elements on your forms.</p>

<h2 id="Validation">Validation</h2>

<p>Radio buttons don't participate in constraint validation; they have no real value to be constrained.</p>

<h2 id="Styling_radio_inputs">Styling radio inputs</h2>

<p>The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this:</p>

<pre class="brush: html notranslate">&lt;form&gt;
  &lt;fieldset&gt;
    &lt;legend&gt;Please select your preferred contact method:&lt;/legend&gt;
    &lt;div&gt;
      &lt;input type="radio" id="contactChoice1"
       name="contact" value="email" checked&gt;
      &lt;label for="contactChoice1"&gt;Email&lt;/label&gt;

      &lt;input type="radio" id="contactChoice2"
       name="contact" value="phone"&gt;
      &lt;label for="contactChoice2"&gt;Phone&lt;/label&gt;

      &lt;input type="radio" id="contactChoice3"
       name="contact" value="mail"&gt;
      &lt;label for="contactChoice3"&gt;Mail&lt;/label&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;/div&gt;
  &lt;/fieldset&gt;
&lt;/form&gt;</pre>

<p>There's not much new to note here except for the addition of {{htmlelement("fieldset")}} and {{htmlelement("legend")}} elements, which help to group the functionality nicely and in a semantic way.</p>

<p>The CSS involved is a bit more significant:</p>

<pre class="brush: css notranslate">html {
  font-family: sans-serif;
}

div:first-of-type {
  display: flex;
  align-items: flex-start;
  margin-bottom: 5px;
}

label {
  margin-right: 15px;
  line-height: 32px;
}

input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;

  border-radius: 50%;
  width: 16px;
  height: 16px;

  border: 2px solid #999;
  transition: 0.2s all linear;
  outline: none;
  margin-right: 5px;

  position: relative;
  top: 4px;
}

input:checked {
  border: 6px solid black;
}

button,
legend {
  color: white;
  background-color: black;
  padding: 5px 10px;
  border-radius: 0;
  border: 0;
  font-size: 14px;
}

button:hover,
button:focus {
  color: #999;
}

button:active {
  background-color: white;
  color: black;
  outline: 1px solid black;
}</pre>

<p>Most notable here is the use of the {{cssxref("-moz-appearance")}} property (with prefixes needed to support some browsers). By default, radio buttons (and <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox">checkboxes</a>) are styled with the operating system's native styles for those controls. By specifying <code>appearance: none</code>, you can remove the native styling altogether, and create your own styles for them. Here we've used a {{cssxref("border")}} along with {{cssxref("border-radius")}} and a {{cssxref("transition")}} to create a nice animating radio selection. Notice also how the {{cssxref(":checked")}} pseudo-class is used to specify the styles for the radio button's appearance when selected.</p>

<p><strong>Compatibility note</strong>: If you wish to use the {{cssxref("appearance")}} property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword <code>none</code> does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers.</p>

<p>{{EmbedLiveSample('Styling_radio_inputs', 600, 120)}}</p>

<p>Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities.</p>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th>Specification</th>
   <th>Status</th>
   <th></th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('HTML WHATWG', 'forms.html#radio-button-state-(type=radio)', '&lt;input type="radio"&gt;')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', 'forms.html#radio-button-state-(type=radio)', '&lt;input type="radio"&gt;')}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("html.elements.input.input-radio")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li>{{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it.</li>
 <li>{{domxref("RadioNodeList")}}: the interface that describes a list of radio buttons</li>
</ul>