更多全局属性
本教程共 110 篇 · 第 101 篇 · 更新于 2026-07-28 · 约 4 分钟阅读
101. 更多全局属性
本节目标:掌握 accesskey、dir、lang、translate、popover、inert、autocapitalize 等更多全局属性,提升页面可访问性和多语言支持。
accesskey:键盘快捷键
给元素绑定一个快捷键,按下后直接聚焦或激活:
<button accesskey="s">保存(Alt+S)</button>
<input accesskey="f" placeholder="按 Alt+F 聚焦">
| 操作系统 | 组合键 |
|---|---|
| Windows/Linux | Alt + 字符 |
| macOS | Ctrl + Alt + 字符 |
| Firefox | Shift + Alt + 字符 |
Warningaccesskey 容易和浏览器或屏幕阅读器的快捷键冲突。实际项目中谨慎使用。如果要实现快捷键,更推荐用 JS 监听
keydown事件。
dir:文字方向
设置文本的排列方向:
<p dir="ltr">从左到右(英文、中文默认)</p>
<p dir="rtl">从右到左(阿拉伯语、希伯来语)</p>
<p dir="auto">自动判断(根据内容)</p>
常用值:
ltr:left to right(从左到右)rtl:right to left(从右到左)auto:自动检测
Tip做国际化应用时,
dir="auto"是个安全的选择。它会自动识别内容语言决定方向。
lang:语言标记
声明元素内容的语言。对以下场景非常重要:
- 屏幕阅读器选择发音
- 浏览器决定是否开启拼写检查
- 搜索引擎理解页面语言
- CSS
:lang()伪类选择
<html lang="zh-CN">
<body>
<p>这是中文</p>
<p lang="en">This is English</p>
<p lang="ar" dir="rtl">هذا عربي</p>
</body>
</html>
常用语言代码:
| 代码 | 语言 |
|---|---|
zh-CN | 简体中文 |
zh-TW | 繁体中文 |
en | 英文 |
ja | 日文 |
ko | 韩文 |
ar | 阿拉伯语 |
Note
<html lang="...">一定要写。不加的话,屏幕阅读器可能用错误的发音读你的中文页面。
translate:控制翻译
告诉浏览器这个内容要不要被翻译:
<p translate="no">brandName 不应该被翻译</p>
<p translate="yes">这段可以被翻译</p>
浏览器或翻译插件遇到 translate="no" 的内容会跳过。适合品牌名、代码片段、人名。
popover:弹出层
HTML5 新加的声明式弹出层。不需要 JS 就能实现点击显示/隐藏:
<button popovertarget="my-popup">打开弹窗</button>
<div id="my-popup" popover>
<p>我是弹出内容</p>
<button popovertarget="my-popup" popovertarget-action="hide">关闭</button>
</div>
值可以是:
auto(默认):点击外部自动关闭manual:需要手动关闭
<div id="my-popup" popover="manual">
这个弹窗不会自动关闭
</div>
Notepopover 是较新的特性。主流浏览器从 2023 年底开始支持。如果需要兼容老浏览器,可以用 JS 方案或
<dialog>标签替代。
inert:禁止交互
让元素及其子元素”变聋”——不能点击、不能聚焦、不能 Tab 到:
<div inert>
<button>这个按钮点不了</button>
<input>这个输入框聚焦不了
</div>
常见用途:
- 模态弹窗打开时,背后的内容不可操作
- 页面加载完成前的占位区域
// 打开弹窗时,让背景变 inert
document.getElementById("main").inert = true;
// 关闭弹窗时恢复
document.getElementById("main").inert = false;
autofocus:自动聚焦
页面加载时自动聚焦到该元素:
<input autofocus placeholder="页面加载后光标自动在这里">
Warning一个页面只用一次 autofocus。自动聚焦会抢走用户的控制权,移动端还可能导致键盘弹出。谨慎使用。
autocapitalize:移动端键盘大小写
控制移动端虚拟键盘的大小写行为:
<input autocapitalize="off"> <!-- 全小写 -->
<input autocapitalize="on"> <!-- 首字母大写 -->
<input autocapitalize="words"> <!-- 每个单词首字母大写 -->
<input autocapitalize="sentences"> <!-- 句子首字母大写 -->
| 值 | 效果 |
|---|---|
off | 关闭自动大写 |
on/sentences | 句首字母大写 |
words | 每个单词首字母大写 |
characters | 全部大写 |
适合场景:
- 用户名输入框 →
off - 姓名输入框 →
words - 邮箱输入框 →
off
autocorrect:自动纠正(Safari)
Safari 专用,关闭自动纠正:
<input autocorrect="off">
速查表
| 属性 | 用途 | 值 |
|---|---|---|
accesskey | 快捷键 | 单个字符 |
dir | 文本方向 | ltr/rtl/auto |
lang | 语言标记 | 语言代码 |
translate | 翻译开关 | yes/no |
popover | 弹出层 | auto/manual |
inert | 禁止交互 | 布尔 |
autofocus | 自动聚焦 | 布尔 |
autocapitalize | 键盘大小写 | off/on/words/sentences |
Tip
lang、dir、inert这几个属性对无障碍体验和国际化最有用。养成习惯,多语言站点必加lang和dir。