我看到很多帖子都在讨论“当涉及 HTML 按钮时,我想为我的特定情况创建一个特定的按钮”。如果可以的话,我想在这里一次性得到专业人士的意见:
在 HTML 中制作按钮时,什么情况下最好使用以下方式:
在 HTML 中制作按钮时,什么情况下最好使用以下方式:
<a>
?<button>
?<div>
?<input type='button'>
?
<a>
?<button>
?<div>
?<input type='button'>
?有一篇好文章很好地概括了它们之间的差异。
简而言之:
| | General usage | Complex designs | Can be disabled |
|-----------------------|----------------------------|-----------------|-----------------|
| <button> | General button purpose. | Yes | Yes |
| | Used in most cases | | |
| --------------------- | -------------------------- | --------------- | --------------- |
| <input type="button"> | Usually used inside | No | Yes |
| | forms | | |
| --------------------- | -------------------------- | --------------- | --------------- |
| <a> | Used to navigate to | Yes | No |
| | pages and resources | | |
| --------------------- | -------------------------- | --------------- | --------------- |
| <div> | Can be used for clickable | Yes | No |
| | area which is not button | | |
| | or link by definition | | |
通常,我尽量以最具“语义化”和实用性的方式使用HTML标记:
<a>
标记:a代表“锚点”,在按钮是链接到页面上或外部内容时我会使用它;div
标记:这是一个简单的容器。当我需要做没有任何特定工作但非常自定义的样式(例如简单动画、过渡、打开模式等)的按钮时,我使用它。这是多才多艺的标记。<button>
标记:根据W3规范,这是创建页面按钮的标准标记,因此在需要onClick()等操作时使用它。<input type="button">
标记:与button标记相同,但您需要它进行表单提交,因为使用<button>
提交表单可能提交不同的值。我通常在表单上使用它。