最小的例子
let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled = true;
document.body.appendChild(input);
.number-input:focus {
background: yellow;
}
.number-input {
-moz-appearance: textfield;
}
<button onClick="document.getElementById('input').disabled = false">
Enable
</button>
<button onClick="document.getElementById('input').disabled = true">
Disable
</button>
创建的input
在启动时被半禁用,i。即你可以点击它,它变成黄色(获得焦点),但你不能写一个数字。但是,单击“启用”后单击“禁用”按钮后,它将按预期禁用。这似乎是一个涉及input.type = "number"
和浏览器特定-moz-appearance: textfield
的错误,我用它来隐藏向上和向下按钮。
在加载页面时,如何真正禁用输入字段的任何想法?
答案 0 :(得分:1)
将input[disabled] {pointer-events:none}
添加到CSS似乎解决了这个问题。不知道为什么Firefox仍然允许这样的初始焦点。
但是,此CSS修补程序将only work in browsers that support pointer-events
属性。 IE支持很差(只有11)。还有一个user-select
属性可以工作(尚未测试),但仍然允许输入的数据以表格形式提交,并且可能会再次受到浏览器支持的限制。
第三种(可能是非推荐的)选项(在禁用时)在输入前面有一个元素来捕获点击,但这是解决它的一种非常混乱的方式。
另一种可能性:禁用时,您可以让JS为.number-input:focus
let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
document.body.appendChild(input);
input.disabled = true;
.number-input:focus {
background: yellow;
}
.number-input {
-moz-appearance: textfield;
}
input[disabled] {pointer-events:none}
<button onClick="document.getElementById('input').disabled = false">
Enable
</button>
<button onClick="document.getElementById('input').disabled = true">
Disable
</button>
答案 1 :(得分:0)
在Firefox中,它帮助我将禁用设置为input.disabled
。不要问我为什么: - )
let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled; // here instead of input.disabled = true
document.body.appendChild(input);
.number-input:focus {
background: yellow;
}
.number-input {
-moz-appearance: textfield;
}
<button onClick="document.getElementById('input').disabled = false">
Enable
</button>
<button onClick="document.getElementById('input').disabled = true">
Disable
</button>