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
343
344
345
346
347
348
349
350
351
|
---
title: <input type="button">
slug: Web/HTML/Element/Input/button
tags:
- Documentação
- Element
- Elementos Input
- Formulários HTML
- HTML
- Input
- Referencia
- Tipos de Input
- botões
- button
- formulários
translation_of: Web/HTML/Element/input/button
---
<div>{{HTMLRef}}</div>
<p><span class="seoSummary">Elementos {{HTMLElement("input")}} do tipo <strong><code>button</code> </strong>são renderizados como um simples botão, que podem ser programados para controlar funcionalidades customizadas em qualquer lugar de uma página web quando for atribuído um evento (tipicamente para um evento {{event("click")}}).</span></p>
<div>{{EmbedInteractiveExample("pages/tabbed/input-button.html", "tabbed-shorter")}}</div>
<p class="hidden">A fonte para estes exemplos interativos é armazenado em um repositório GitHub. Se você gostaria de contribuir com projetos de exemplos interativos, por favor clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e envie-nos uma requisição pull.</p>
<div class="note">
<p><strong>Nota</strong>: Enquanto elementos <code><input></code> do tipo <code>button</code> ainda são perfeitamente válidos, os novos elementos {{HTMLElement("button")}} são agora os favoráveis meios para criar botões. Uma etiqueta de texto (label) para um {{HTMLElement("button")}} pode ser inserida entre uma tag de abertura e outra de fechamento, podendo ser incluídas até imagens.</p>
</div>
<table class="properties">
<tbody>
<tr>
<td><strong>{{anch("Value")}}</strong></td>
<td>Um {{domxref("DOMString")}} usado como uma etiqueta de botão.</td>
</tr>
<tr>
<td><strong>Eventos</strong></td>
<td>{{event("click")}}</td>
</tr>
<tr>
<td><strong>Atributos comuns suportados</strong></td>
<td>{{htmlattrxref("type", "input")}}, e {{htmlattrxref("value", "input")}}</td>
</tr>
<tr>
<td><strong>atributos IDL</strong></td>
<td><code>value</code></td>
</tr>
<tr>
<td><strong>Métodos</strong></td>
<td>Nenhum</td>
</tr>
</tbody>
</table>
<h2 id="Value">Value</h2>
<p>Seu atributo {{htmlattrxref("value", "input")}} de um elemento <code><input type="button"></code> contém uma {{domxref("DOMString")}} que é usado como uma etiqueta (label) de um botão</p>
<div id="summary-example3">
<pre class="brush: html"><input type="button" value="Click Me"></pre>
</div>
<p>{{EmbedLiveSample("summary-example3", 650, 30)}}</p>
<p>Se você não especificar um <code>value</code>, você obtém um botão vazio:</p>
<div id="summary-example1">
<pre class="brush: html"><input type="button"></pre>
</div>
<p>{{EmbedLiveSample("summary-example1", 650, 30)}}</p>
<h2 id="Usando_buttons">Usando buttons</h2>
<p>Elementos <code><input type="button"></code> não possuem comportamento padrão (seu primos,<code> <a href="/en-US/docs/Web/HTML/Element/input/submit"><input type="submit"></a></code> e <code><a href="/en-US/docs/Web/HTML/Element/input/reset"><input type="reset"></a></code> são usados para submeter e resetar formulários). Para que botões possam fazer algo, você tem de escrever um código em JavaScript para fazê-lo trabalhar.</p>
<h3 id="Um_simples_botão">Um simples botão</h3>
<p>Nós iremos começar criando um simples botão com um evento {{event("click")}} que inicia nossa máquina (bem, ele altera o <code>value</code> do botão e o contéudo texto do seguinte parágrafo):</p>
<pre class="brush: html"><form>
<input type="button" value="Start machine">
</form>
<p>The machine is stopped.</p></pre>
<pre class="brush: js">const button = document.querySelector('input');
const paragraph = document.querySelector('p');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === 'Start machine') {
button.value = 'Stop machine';
paragraph.textContent = 'The machine has started!';
} else {
button.value = 'Start machine';
paragraph.textContent = 'The machine is stopped.';
}
}</pre>
<p>O script recebe uma referência para o objeto {{domxref("HTMLInputElement")}} representando o <code><input></code> no DOM, salvando esta referência na variável <code>button</code>. {{domxref("EventTarget.addEventListener", "addEventListener()")}} é então usado para criar uma função que será chamada quando o evento {{event("click")}} for executado no botão.</p>
<p>{{EmbedLiveSample("A_simple_button", 650, 100)}}</p>
<h3 id="Adicionando_atalhos_de_teclados_aos_botões">Adicionando atalhos de teclados aos botões</h3>
<p>Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any {{HTMLElement("input")}} for which it makes sense — you use the {{htmlattrxref("accesskey")}} global attribute.</p>
<p>In this example, <kbd>s</kbd> is specified as the access key (you'll need to press <kbd>s</kbd> plus the particular modifier keys for your browser/OS combination; see <a href="/en-US/docs/Web/HTML/Global_attributes/accesskey">accesskey</a> for a useful list of those).</p>
<div id="accesskey-example1">
<pre class="brush: html"><form>
<input type="button" value="Start machine" accesskey="s">
</form>
<p>The machine is stopped.</p>
</pre>
</div>
<div class="hidden">
<pre class="brush: js">const button = document.querySelector('input');
const paragraph = document.querySelector('p');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === 'Start machine') {
button.value = 'Stop machine';
paragraph.textContent = 'The machine has started!';
} else {
button.value = 'Start machine';
paragraph.textContent = 'The machine is stopped.';
}
}</pre>
</div>
<p>{{EmbedLiveSample("Adding_keyboard_shortcuts_to_buttons", 650, 100)}}</p>
<div class="note">
<p><strong>Note</strong>: The problem with the above example of course is that the user will not know what the access key is! In a real site, you'd have to provide this information in a way that doesn't intefere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).</p>
</div>
<h3 id="Desativando_e_ativando_um_botão">Desativando e ativando um botão</h3>
<p>To disable a button, simply specify the {{htmlattrxref("disabled")}} global attribute on it, like so:</p>
<div id="disable-example1">
<pre class="brush: html"><input type="button" value="Disable me" disabled></pre>
</div>
<p>You can enable and disable buttons at run time by simply setting <code>disabled</code> to <code>true</code> or <code>false</code>. In this example our button starts off enabled, but if you press it, it is disabled using <code>button.disabled = true</code>. A {{domxref("WindowTimers.setTimeout","setTimeout()")}} function is then used to reset the button back to its enabled state after two seconds.</p>
<div class="hidden">
<h6 id="Hidden_code_1">Hidden code 1</h6>
<pre class="brush: html"><input type="button" value="Enabled"></pre>
<pre class="brush: js">const button = document.querySelector('input');
button.addEventListener('click', disableButton);
function disableButton() {
button.disabled = true;
button.value = 'Disabled';
window.setTimeout(function() {
button.disabled = false;
button.value = 'Enabled';
}, 2000);
}</pre>
</div>
<p>{{EmbedLiveSample("Hidden_code_1", 650, 60)}}</p>
<p>If the <code>disabled</code> attribute isn't specified, the button inherits its <code>disabled</code> state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a {{HTMLElement("fieldset")}} element, and then setting <code>disabled</code> on the container.</p>
<p>The example below shows this in action. This is very similar to the previous example, except that the <code>disabled</code> attribute is set on the <code><fieldset></code> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.</p>
<div class="hidden">
<h6 id="Hidden_code_2">Hidden code 2</h6>
<pre class="brush: html"><fieldset>
<legend>Button group</legend>
<input type="button" value="Button 1">
<input type="button" value="Button 2">
<input type="button" value="Button 3">
</fieldset></pre>
<pre class="brush: js">const button = document.querySelector('input');
const fieldset = document.querySelector('fieldset');
button.addEventListener('click', disableButton);
function disableButton() {
fieldset.disabled = true;
window.setTimeout(function() {
fieldset.disabled = false;
}, 2000);
}</pre>
</div>
<p>{{EmbedLiveSample("Hidden_code_2", 650, 60)}}</p>
<div class="note">
<p><strong>Note</strong>: Firefox will, unlike other browsers, by default, <a href="http://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing">persist the dynamic disabled state</a> of a {{HTMLElement("button")}} across page loads. Use the {{htmlattrxref("autocomplete","button")}} attribute to control this feature.</p>
</div>
<h2 id="Validação">Validação</h2>
<p>Buttons não participam na validação; eles não tem um valor real para ser restringido.</p>
<h2 id="Exemplos">Exemplos</h2>
<p>The below example shows a very simple drawing app created using a {{htmlelement("canvas")}} element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas.</p>
<pre class="brush: html"><div class="toolbar">
<input type="color" aria-label="select pen color">
<input type="range" min="2" max="50" value="30" aria-label="select pen size"><span class="output">30</span>
<input type="button" value="Clear canvas">
</div>
<canvas class="myCanvas">
<p>Add suitable fallback here.</p>
</canvas></pre>
<div class="hidden">
<pre class="brush: css">body {
background: #ccc;
margin: 0;
overflow: hidden;
}
.toolbar {
background: #ccc;
width: 150px;
height: 75px;
padding: 5px;
}
input[type="color"], input[type="button"] {
width: 90%;
margin: 0 auto;
display: block;
}
input[type="range"] {
width: 70%;
}
span {
position: relative;
bottom: 5px;
}</pre>
</div>
<pre class="brush: js">var canvas = document.querySelector('.myCanvas');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight-85;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(0,0,0)';
ctx.fillRect(0,0,width,height);
var colorPicker = document.querySelector('input[type="color"]');
var sizePicker = document.querySelector('input[type="range"]');
var output = document.querySelector('.output');
var clearBtn = document.querySelector('input[type="button"]');
// covert degrees to radians
function degToRad(degrees) {
return degrees * Math.PI / 180;
};
// update sizepicker output value
sizePicker.oninput = function() {
output.textContent = sizePicker.value;
}
// store mouse pointer coordinates, and whether the button is pressed
var curX;
var curY;
var pressed = false;
// update mouse pointer coordinates
document.onmousemove = function(e) {
curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
canvas.onmousedown = function() {
pressed = true;
};
canvas.onmouseup = function() {
pressed = false;
}
clearBtn.onclick = function() {
ctx.fillStyle = 'rgb(0,0,0)';
ctx.fillRect(0,0,width,height);
}
function draw() {
if(pressed) {
ctx.fillStyle = colorPicker.value;
ctx.beginPath();
ctx.arc(curX, curY-85, sizePicker.value, degToRad(0), degToRad(360), false);
ctx.fill();
}
requestAnimationFrame(draw);
}
draw();</pre>
<p>{{EmbedLiveSample("Examples", '100%', 600)}}</p>
<h2 id="Específicações">Específicações</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comments</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('HTML WHATWG', 'forms.html#button-state-(type=button)', '<input type="button">')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('HTML5 W3C', 'forms.html#button-state-(type=button)', '<input type="button">')}}</td>
<td>{{Spec2('HTML5 W3C')}}</td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Compatibilidade com navegadores</h2>
<p>{{Compat("html.elements.input.input-button")}}</p>
<h2 id="Veja_também">Veja também</h2>
<ul>
<li>{{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it.</li>
<li>The more modern {{HTMLElement("button")}} element.</li>
<li><a href="/en-US/docs/Learn/HTML/Forms/Property_compatibility_table_for_form_widgets">Compatibility of CSS properties</a></li>
</ul>
|