自动聚焦 autofocus 属性

3/10/2021 CSS

# HTML5 自动聚焦 autofocus 属性

# 定义

  • autofocus 属性是一个布尔属性
  • autofocus 属性为 true 时,页面加载时自动聚焦到此控件
  • 支持 autofocus 属性的标签有 input、textarea、button

# 使用

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>autofocus的使用</title>
    </head>
    <body>
        <div align="center">文本内容回居中显示,因为元素上面的设置了</div>
        <div class="div">我是一个很高的地址</div>
        <button autofocus>我有自动聚集功能,加载到这里</button>
        <style>
            .div {
                height: 2000px;
            }
            div {
                border: 1px red solid;
            }
        </style>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

点击我查看 demo 效果 (opens new window)

# 如果一个页面中有多个表单元素设置了 autofocus 呢

经测试验证会聚焦到第一个设置 autofocus 为 true 的元素

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>autofocus的使用</title>
    </head>
    <body>
        <button autofocus>我是第一个自动聚焦的按钮</button>
        <div align="center">文本内容回居中显示,因为元素上面的设置了</div>
        <div class="div">我是一个很高的地址</div>
        <button autofocus>我有自动聚集功能,加载到这里</button>
        <style>
            .div {
                height: 2000px;
            }
            div {
                border: 1px red solid;
            }
        </style>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

注意 ⚠️:给 div、h1 等纯显示元素设置 autofocus 没有效果。

# 应用场景

谷歌、百度等搜索页面,页面一旦加载,光标就定位在输入框里。

上次更新: 3/22/2021, 3:28:01 PM