readonly 属性仅对文本类 input(如 text、password、email 等)和 textarea 生效,对 checkbox、radio、select、button 无效;HTML 中应写为 readonly(无值),JS 中设只读用 el.readOnly = true 或 setAttribute('readonly', ''),移除用 removeAttribute('readonly');它不阻止用户篡改,后端必须校验。

readonly 属性只对特定 input 类型生效
它不是万能开关,仅作用于 <input type="text">、<input type="password">、<input type="email">、<input type="tel">、<input type="url">、<input type="search">、<input type="date"> 等文本类控件,以及 <textarea>。对 <input type="checkbox">、<input type="radio">、<select>、<button> 加 readonly 会被浏览器直接忽略——不报错,也不起效。
HTML 中怎么写才真正生效
直接写布尔属性名即可,无需赋值:
<input type="text" value="U-7890" name="order_id" readonly>
常见错误包括:
-
readonly="true"或readonly="false"—— 浏览器只看属性是否存在,不解析字符串值; -
readonly=""虽然技术上可行,但语义不清,建议统一用无值写法; - XHTML 场景下才需写成
readonly="readonly",现代 HTML5 不需要。
JavaScript 动态控制 readonly 的坑点
用 JS 切换状态时,容易因兼容性或大小写出错:
立即学习“前端免费学习笔记(深入)”;
- 设为只读:
el.readOnly = true✅(注意是readOnly,驼峰写法)或el.setAttribute('readonly', '')✅; - 恢复可编辑:
el.removeAttribute('readonly')✅(比el.readOnly = false更可靠,尤其在 Safari 15 及更早版本中); - React/Vue 中绑定要拼对:Vue 是
:readonly="isLocked",React 是readOnly={isLocked}; - 别忘了同步处理
tabindex:加了readonly后仍可 Tab 进去,光标闪烁却无法输入,体验割裂。
readonly 不等于防篡改,后端必须校验
用户可通过开发者工具删掉 readonly 属性、粘贴内容、拖拽文本,甚至执行 input.value = 'new' 直接修改——这些操作浏览器都允许。关键点在于:
-
readonly字段的值仍会出现在FormData、form.serialize()和提交的 query string 中; -
disabled字段则完全不参与提交; - 若该字段承载业务关键信息(如用户 ID、订单号),后端必须做一致性校验(比如比对数据库原始值、签名或时间戳),不能信任前端传来的任何
readonly值。
它只是前端交互层的友好提示,不是数据安全层的锁。



















