HTML 解决方案

可以在没有 Javascript 的 HTML 表单上设置默认输入焦点。

这可以在 HTML5 中完成,因为它允许我们在表单元素上使用 autofocus 属性。

设置默认表单焦点的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <input type="text" name="myInput" autofocus />
  </body>
</html>

在上面的示例中,我们使用了一个 <input> 元素并为其添加了 autofocus 属性。

让我们看另一个例子,我们使用了几个 <input> 元素,并且只其中一个元素上设置了 autofocus 属性。

仅为一个 <input> 元素设置焦点的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题.</title>
    <style>
      div {
        margin-bottom: 10px;
      }
      label {
        display: inline-block;
        width: 70px;
      }
    </style>
    <body>
      <h1>Example</h1>
      <form action="/form/submit" method="get">
        <div>
          <label for="name">Name:</label>
          <input type="text" id="name" name="name" autofocus>
        </div>
        <div>
          <label for="surname">Surname:</label>
          <input type="text" id="surname" name="surname">
        </div>
        <div>
          <label for="year">Year:</label>
          <input type="number" id="year" name="year" value="2015" disabled>
        </div>
        <input type="submit">
      </form>
    </body>
</html>

对于第一个 <input>,我们设置了 autofocus 属性,对于第三个 <input>,我们设置了 disabled 属性。

其中我们还使用了一些 CSS 并为 <div> 元素设置了 margin-bottom 属性,并为 <label> 元素指定了“inline-block”值和 width 属性的 display 属性。

如何在没有 Javascript 的情况下设置默认的 HTML 表单焦点
日期:2020-06-02 22:15:12 来源:oir作者:oir