<button> vs. <input type="button"> -- which to use?

技术背景

在HTML中,<button><input type="button">都可以用来创建按钮,但在不同场景下它们各有优劣。随着时间推移和浏览器的发展,对于两者的选择也有了一些变化。

实现步骤

<button>的使用

1
<button type="button">Click Me!</button>

<button>可以在表单内外使用,默认情况下,如果在表单中且没有指定type属性,它会表现得像type="submit"。它可以包含文本、图片等HTML内容,还支持CSS伪元素。

<input type="button">的使用

1
<input type="button" value="Click Me!">

<input type="button">只能在表单中使用,要使其作为提交按钮,需要将type属性设置为submit。它只能包含文本内容,不支持CSS伪元素。

核心代码

以下是一个简单的表单示例,展示了两者的使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button vs Input</title>
</head>
<body>
<form action="#">
<input type="text" name="example" placeholder="Enter something">
<input type="button" value="Input Button">
<button type="button">Button Element</button>
</form>
</body>
</html>

最佳实践

  • 优先使用<button>:在现代浏览器中,<button>提供了更丰富的渲染可能性,能包含HTML内容,方便使用CSS伪元素进行样式设计。
  • 考虑兼容性:如果需要支持IE < 11,可以考虑使用<input type="button">
  • 表单提交场景:若要在表单中创建提交按钮,且关注不同浏览器提交值的一致性,建议使用<input type="submit">

常见问题

  1. 表单提交问题<button>默认会提交表单,若不想提交,需指定type="button";而<input type="button">需将type设置为submit才会提交表单。
  2. 内容问题<button>可以包含HTML内容,而<input type="button">只能包含文本。
  3. CSS样式问题<button>更容易通过CSS进行样式设计,且样式在不同浏览器中表现更一致;<input type="button">的样式在不同浏览器中可能有差异。
  4. jQuery事件问题:jQuery对<input>的事件支持更多,如focusblur,而对<button>仅支持click事件。
  5. IE问题:IE不恰当检测<button>value属性,会使用标签内容作为值;所有表单值都会发送到服务器端,使用<button type="submit">会比较麻烦。
  6. iOS Safari问题<button>disabled属性在iOS Safari中可能无法正常工作。

<button> vs. <input type="button"> -- which to use?
https://119291.xyz/posts/button-vs-input-type-button-which-to-use/
作者
ww
发布于
2025年5月26日
许可协议