Baseline Widely availableThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Learn moreSee full compatibilityReport feedbackbutton 类型的 元素被渲染为简单的按钮,可以根据需要对其进行编程,可以为其分配一个事件处理函数(通常为 click 事件),以控制网页上的任何地方的自定义功能。
尝试一下
.styled {
border: 0;
line-height: 2.5;
padding: 0 20px;
font-size: 1rem;
text-align: center;
color: #fff;
text-shadow: 1px 1px 1px #000;
border-radius: 10px;
background-color: rgb(220 0 0 / 100%);
background-image: linear-gradient(
to top left,
rgb(0 0 0 / 20%),
rgb(0 0 0 / 20%) 30%,
rgb(0 0 0 / 0%)
);
box-shadow:
inset 2px 2px 3px rgb(255 255 255 / 60%),
inset -2px -2px 3px rgb(0 0 0 / 60%);
}
.styled:hover {
background-color: rgb(255 0 0 / 100%);
}
.styled:active {
box-shadow:
inset -2px -2px 3px rgb(255 255 255 / 60%),
inset 2px 2px 3px rgb(0 0 0 / 60%);
}
备注: button 类型的 元素仍然是合法的 HTML 代码,但是新的
值含有值的按钮 的 value 属性包含用作按钮标签的字符串。
html
不含有值的按钮如果没有指定 value,会得到一个空的按钮:
html
使用按钮 元素没有默认行为(与之类似的 和 分别用于提交和重置表单)。要让按钮做任何事情,你必须编写 JavaScript 代码。
简单的按钮我们从创建一个具有 click 事件处理器的按钮开始,它启动了我们的机器(同时,也切换了按钮的 value 和下列段落的文字):
html
机器已经停下了。
jsconst button = document.querySelector("input");
const paragraph = document.querySelector("p");
button.addEventListener("click", updateButton);
function updateButton() {
if (button.value === "开动机器") {
button.value = "停止机器";
paragraph.textContent = "机器启动了!";
} else {
button.value = "开动机器";
paragraph.textContent = "机器已经停下了。";
}
}
脚本获得了对 DOM 中代表 的 HTMLInputElement 对象的引用,并将此引用保存在变量 button 中。然后,addEventListener() 被用来建立一个函数,当按钮上发生 click 事件时,该函数将被运行。
为按钮添加键盘快捷方式键盘快捷键可以让用户使用键盘上的某个键或组合键来触发一个按钮。要为一个按钮添加键盘快捷键——就像对任何 都有意义的那样——你可以使用 accesskey 全局属性。
在这个例子中,s 被指定成为访问键,你需要按住浏览器或操作系统所指定的组合键加上 s 键来触发按钮,参见 accesskey 以获取一些有用的列表。
html
机器已经停下了。
const button = document.querySelector("input");
const paragraph = document.querySelector("p");
button.addEventListener("click", updateButton);
function updateButton() {
if (button.value === "开动机器") {
button.value = "停止机器";
paragraph.textContent = "机器启动了!";
} else {
button.value = "开动机器";
paragraph.textContent = "机器已经停下了。";
}
}
备注:
当然,上述例子的问题是,用户将不知道访问键是什么!在一个真实的网站中,你必须以一种不影响网站设计的方式来提供这些信息(例如,提供一个容易访问的链接,指向关于网站访问键是什么的信息)。
禁用和启用按钮要禁用按钮,在其上指定 disabled 全局属性,就像这样:
html
设置禁用属性
你可以在运行时通过设置 disabled 为 true 或 false 来启用和禁用按钮。在这个例子中,我们的按钮一开始是启用的,但如果你按下它,就会用 button.disabled = true 将其禁用。然后,一个 setTimeout() 函数被用来在两秒后将按钮重置为启用状态。
html
jsconst button = document.querySelector("input");
button.addEventListener("click", disableButton);
function disableButton() {
button.disabled = true;
button.value = "已禁用";
setTimeout(() => {
button.disabled = false;
button.value = "已启用";
}, 2000);
}
继承禁用状态
如果没有指定 disabled 属性,按钮将从其父元素继承其 disabled 状态。这使得一次启用和禁用一组元素成为可能,方法是将它们包围在一个容器中,如