【问题标题】:Preselect text input on page load在页面加载时预选文本输入
【发布时间】:2013-11-06 17:59:01
【问题描述】:

我不希望用户必须单击第一个文本框才能在其上书写。加载页面时,我希望预先选择文本输入。

【问题讨论】:

标签: javascript html input


【解决方案1】:

在 html 元素中使用 autofocus 属性。

在本例中,您可以看到“名字”输入具有自动对焦功能,并且在页面加载时会自动选择,因此用户可以直接输入:

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp">
  First name: <input type="text" name="fname" autofocus><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit">
</form>

</body>
</html>

Internet Explorer 9 及更早版本不支持 input 标签的 autofocus 属性。

【讨论】:

    【解决方案2】:

    这很简单。这是fiddle

    HTML

    <input id="box" value="text" />
    

    JavaScript

    window.onload = document.getElementById('box').select();
    

    【讨论】:

      【解决方案3】:

      使用javascript HTMLElement.focus()的基本示例

      <head>
          <script type="text/javascript">
              function setFocus() {
                  document.getElementById('txtTwo').focus();
              }
          </script>
      </head>
      <body onload="setFocus();">
              <input id="txtOne" type="text" />
              <br/>
              <input id="txtTwo" type="text" />
      </body>
      

      【讨论】:

        猜你喜欢
        • 2016-05-11
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多