阅读(1953)

HTML 表单按钮

最后一次修改 2017年08月03日

HTML表单按钮

有三种方法可以使用按钮通过设置三个不同的type属性。

  • submit - 指定该按钮将用于提交表单

  • reset - 指定该按钮将用于重置表单

  • button - 指定按钮没有特定的语义意义

提交按钮 - 提交表单

当您设置要submit按钮的type属性时,按下按钮将提交包含按钮的表单。

这是未应用 type 属性时的默认行为。

提交按钮具有以下列出的一些附加属性。

  • form - 指定与按钮相关联的一个或多个表单。

  • formaction - 覆盖表单元素上的操作属性,并指定要提交的新URL。

  • formenctype - 覆盖表单元素上的enctype属性,并指定表单数据的编码方案。

  • formmethod - 覆盖表单元素上的方法属性。

  • formtarget - 覆盖表单元素上的target属性。

  • formnovalidate - 覆盖表单上的novalidate属性以指定是否应执行客户端验证。

以下代码显示了如何将这些属性应用于按钮元素。

<!DOCTYPE HTML>
<html>
<body>
  <form>
    <p>
      <label for="fave">Fruit: 
      <input autofocus id="fave" name="fave" /></label>
    </p>
    <p>
      <label for="name">Name: 
      <input id="name" name="name" /></label>
    </p>
    <button type="submit" 
            formaction="http://example.com/form"
          formmethod="post">Submit Vote</button>
  </form>
</body>
</html>

上面的代码从表单元素中省略了action和method属性,并通过button元素上的 formaction formmethod 属性提供了配置。

重置按钮 - 重置表单

如果将某个buttontype属性设置为reset ,则按下该按钮可将表单中的所有输入元素重置为其初始状态。

重置按钮没有其他属性。

以下代码显示了向HTML文档添加重置按钮。

<!DOCTYPE HTML>
<html>
<body>
  <form method="post" action="http://example.com/form">
    <p>
      <label for="fave">Fruit: 
      <input autofocus id="fave" name="fave" /></label>
    </p>
    <p>
      <label for="name">Name: <input id="name" name="name" /></label>
    </p>
    <button type="submit">Submit Vote</button>
    <button type="reset">Reset</button>
  </form>
</body>
</html>

通用按钮

如果将type属性设置为button,则创建一个普通按钮。它没有特殊的意义,不会做任何事情,当你按它。

以下代码显示了一个通用按钮。

<!DOCTYPE HTML>
<html>
<body>
  <form method="post" action="http://example.com/form">
    <p>
      <label for="fave">Fruit: <input autofocus id="fave"
        name="fave" /></label>
    </p>
    <p>
      <label for="name">Name: <input id="name" name="name" /></label>
    </p>
    <button type="button">
      Do <strong>NOT</strong> press this button
    </button>
  </form>
</body>
</html>

您可以对按钮元素中包含的文本设置样式。

图像按钮

<html>
<body>
    <form action="" method="post">
        <button type="submit">Submit</button>
        <br /><br />
        <button type="reset"><b>Clear this form</b> I want to start again</button>
        <br /><br />
        <button type="button"><img src="http://www.html.cn/style/download.png" alt="submit" /></button>
    </form>
</body>
</html>