如何根据后端传递的editable变量通过JS动态修改input的CSS编辑属性
实现方案
方案1:服务端渲染直接控制(推荐,无需额外JS执行)
- 首先修改你的CSS代码,新增可编辑状态下的样式覆盖规则:
input { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } /* 新增可编辑状态规则 */ .editable-mode input { -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; /* 若之前给input设置了pointer-events: none,也可以在这里解开 */ pointer-events: auto; }
- 在页面根节点(如body标签)渲染时,根据
editable变量动态注入类名:
<body class="<%= editable ? 'editable-mode' : '' %>">
方案2:前端JS动态控制
首先修正你原有逻辑的错误:你给<%= editable %>套了单引号,会把布尔值转成字符串'true'/'false',在JS中'true' == true的判断结果为false,逻辑不会生效,需要去掉引号直接输出布尔值,参考代码如下:
if (<%= editable %>) { // 方式1:给body加类复用方案1的CSS规则(推荐,样式逻辑分离) document.body.classList.add('editable-mode') // 方式2:直接修改所有input的行内样式 // document.querySelectorAll('input').forEach(input => { // input.style.webkitUserSelect = 'text' // input.style.mozUserSelect = 'text' // input.style.msUserSelect = 'text' // input.style.userSelect = 'text' // // 如果input原本设置了readonly属性,需要同步移除才能正常输入 // input.removeAttribute('readonly') // }) }
注意:如果你的input标签原本加了
readonly属性,仅修改user-select只能让用户选中内容,无法修改输入值,需要同步移除readonly属性才能实现完全可编辑。
内容的提问来源于stack exchange,提问作者helplessdev
相关产品推荐
相关产品推荐

