<input type="button">
button
类型的 <input>
元素呈现为简单的按钮,在分配事件处理函数(通常用于 click
事件)时,可以对其进行编程以根据需要控制网页上任何位置的自定义功能。
¥<input>
elements of type button
are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the click
event).
Try it
注意:虽然
button
类型的<input>
元素仍然是完全有效的 HTML,但较新的<button>
元素现在是创建按钮的首选方式。鉴于<button>
的标签文本插入在开始标签和结束标签之间,你可以在标签中包含 HTML,甚至图片。¥Note: While
<input>
elements of typebutton
are still perfectly valid HTML, the newer<button>
element is now the favored way to create buttons. Given that a<button>
's label text is inserted between the opening and closing tags, you can include HTML in the label, even images.
值
带有值的按钮
¥Button with a value
<input type="button">
元素的 value
属性包含一个用作按钮标签的字符串。value
为按钮提供 accessible description。
¥An <input type="button">
elements' value
attribute contains a string that is used as the button's label. The value
provides the accessible description for the button.
<input type="button" value="Click Me" />
没有值的按钮
使用按钮
¥Using buttons
<input type="button">
元素没有默认行为(它们的表亲 <input type="submit">
和 <input type="reset">
分别用于提交和重置表单)。要让按钮执行任何操作,你必须编写 JavaScript 代码来完成该工作。
¥<input type="button">
elements have no default behavior (their cousins, <input type="submit">
and <input type="reset">
are used to submit and reset forms, respectively). To make buttons do anything, you have to write JavaScript code to do the work.
一个简单的按钮
¥A simple button
我们将首先创建一个简单的按钮,其中包含启动我们的机器的 click
事件处理程序(好吧,它会切换按钮的 value
和下一段的文本内容):
¥We'll begin by creating a simple button with a click
event handler that starts our machine (well, it toggles the value
of the button and the text content of the following paragraph):
<form>
<input type="button" value="Start machine" />
</form>
<p>The machine is stopped.</p>
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.";
}
}
该脚本获取对 DOM 中代表 <input>
的 HTMLInputElement
对象的引用,并将该引用保存在变量 button
中。然后,addEventListener()
用于建立一个函数,该函数将在按钮上发生 click
事件时运行。
¥The script gets a reference to the HTMLInputElement
object representing the <input>
in the DOM, saving this reference in the variable button
. addEventListener()
is then used to establish a function that will be run when click
events occur on the button.
向按钮添加键盘快捷键
¥Adding keyboard shortcuts to buttons
键盘快捷键也称为访问键和键盘等效项,允许用户使用键盘上的一个键或多个键组合来触发按钮。要向按钮添加键盘快捷键(就像使用任何有意义的 <input>
一样),你可以使用 accesskey
全局属性。
¥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 <input>
for which it makes sense — you use the accesskey
global attribute.
在此示例中,s 被指定为访问键(你需要按 s 加上适合你的浏览器/操作系统组合的特定修饰键;有关有用的列表,请参阅 accesskey)。
¥In this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).
<form>
<input type="button" value="Start machine" accesskey="s" />
</form>
<p>The machine is stopped.</p>
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.";
}
}
注意:当然,上面示例的问题是用户不知道访问密钥是什么!在真实的站点中,你必须以不干扰站点设计的方式提供此信息(例如,通过提供易于访问的链接来指向有关站点访问密钥的信息)。
¥Note: 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 interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).
禁用和启用按钮
¥Disabling and enabling a button
要禁用按钮,请在其上指定 disabled
全局属性,如下所示:
¥To disable a button, specify the disabled
global attribute on it, like so:
<input type="button" value="Disable me" disabled />
设置禁用属性
¥Setting the disabled attribute
你可以通过将 disabled
设置为 true
或 false
在运行时启用和禁用按钮。在此示例中,我们的按钮一开始处于启用状态,但如果按下它,则会使用 button.disabled = true
禁用它。然后使用 setTimeout()
功能在两秒后将按钮重置回其启用状态。
¥You can enable and disable buttons at run time by setting disabled
to true
or false
. In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true
. A setTimeout()
function is then used to reset the button back to its enabled state after two seconds.
<input type="button" value="Enabled" />
const button = document.querySelector("input");
button.addEventListener("click", disableButton);
function disableButton() {
button.disabled = true;
button.value = "Disabled";
setTimeout(() => {
button.disabled = false;
button.value = "Enabled";
}, 2000);
}
继承禁用状态
¥Inheriting the disabled state
如果未指定 disabled
属性,按钮将从其父元素继承其 disabled
状态。这样就可以通过将元素组封装在容器(例如 <fieldset>
元素)中,然后在容器上设置 disabled
来一次性启用和禁用元素组。
¥If the disabled
attribute isn't specified, the button inherits its disabled
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 <fieldset>
element, and then setting disabled
on the container.
下面的示例展示了这一点的实际效果。这与前面的示例非常相似,不同之处在于,当按下第一个按钮时,在 <fieldset>
上设置 disabled
属性 - 这会导致所有三个按钮都被禁用,直到两秒超时过去。
¥The example below shows this in action. This is very similar to the previous example, except that the disabled
attribute is set on the <fieldset>
when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.
<fieldset>
<legend>Button group</legend>
<input type="button" value="Button 1" />
<input type="button" value="Button 2" />
<input type="button" value="Button 3" />
</fieldset>
const button = document.querySelector("input");
const fieldset = document.querySelector("fieldset");
button.addEventListener("click", disableButton);
function disableButton() {
fieldset.disabled = true;
setTimeout(() => {
fieldset.disabled = false;
}, 2000);
}
注意:与其他浏览器不同,Firefox 即使在页面重新加载后也会保留
<input>
元素的disabled
状态。作为解决方法,请将<input>
元素的autocomplete
属性设置为off
。(更多详情请参见 火狐错误 654072。)¥Note: Unlike other browsers, Firefox persists the
disabled
state of an<input>
element even after the page is reloaded. As a workaround, set the<input>
element'sautocomplete
attribute tooff
. (See Firefox bug 654072 for more details.)
验证
示例
¥Examples
下面的示例显示了一个使用 <canvas>
元素和一些简单的 CSS 和 JavaScript 创建的非常简单的绘图应用(为了简洁起见,我们将隐藏 CSS)。顶部的两个控件允许你选择绘图笔的颜色和大小。单击该按钮时,会调用一个清除画布的函数。
¥The below example shows a very simple drawing app created using a <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.
<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>
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;
}
const canvas = document.querySelector(".myCanvas");
const width = (canvas.width = window.innerWidth);
const height = (canvas.height = window.innerHeight - 85);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(0 0 0)";
ctx.fillRect(0, 0, width, height);
const colorPicker = document.querySelector('input[type="color"]');
const sizePicker = document.querySelector('input[type="range"]');
const output = document.querySelector(".output");
const clearBtn = document.querySelector('input[type="button"]');
// covert degrees to radians
function degToRad(degrees) {
return (degrees * Math.PI) / 180;
}
// update sizepicker output value
sizePicker.oninput = () => {
output.textContent = sizePicker.value;
};
// store mouse pointer coordinates, and whether the button is pressed
let curX;
let curY;
let pressed = false;
// update mouse pointer coordinates
document.onmousemove = (e) => {
curX = e.pageX;
curY = e.pageY;
};
canvas.onmousedown = () => {
pressed = true;
};
canvas.onmouseup = () => {
pressed = false;
};
clearBtn.onclick = () => {
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();
技术总结
规范
Specification |
---|
HTML Standard # button-state-(type=button) |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
<input>
和实现它的HTMLInputElement
接口。- 更现代的
<button>
元素。 - CSS 属性的兼容性