HTML5 自动聚焦 autofocus 属性

本文详细介绍了HTML5中的autofocus属性,包括其定义、使用方式及注意事项。当autofocus属性设置为true时,页面加载时将自动聚焦到指定控件,如input、textarea或button等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

点击我查看 demo 效果

如果一个页面中有多个表单元素设置了 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>

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

应用场景

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值