如何生成一个具有默认起始值且不可更改的输入元素?例如,我正在寻找用户的号码,但我希望'333'已经在输入文本框中,因为所有输入都将以该号码开头。我也不希望用户能够更改它。我需要将333作为值的一部分,而不是仅仅通过样式添加,因为我需要对其进行验证。
答案 0 :(得分:1)
我使用2个输入,如William B所建议,但我会考虑是使用disabled
属性还是readonly
属性。 disabled
属性不允许第一个输入被聚焦,默认的浏览器样式将为其提供灰色背景。 readonly
属性将允许它被聚焦,并且可能具有更理想的初始样式。
答案 1 :(得分:1)
使用JavaScript的一种可能性:
nine = document.getElementById("nine");
nine.addEventListener("keydown", function (ev) {
var el = this;
var value = el.value;
setTimeout(function () {
if (el.value.indexOf("333") != 0) {
el.value = value;
}
}, 0);
});
<input type="text" value="333" id="nine" />
答案 2 :(得分:0)
我建议使用2个看起来像单个输入的输入,第一个输入只读。看到这个小提琴:https://jsfiddle.net/39whrqup/2/
<input readonly value="333" class="static-input">
<input class="nonstatic-input">
.static-input {
margin-right: -20px;
width: 50px;
border: 0;
}
.nonstatic-input {
border: 0;
}
在阅读用户输入时,您必须自然地添加静态部分:
var userInput = document.querySelector('input.static-input').value +
document.querySelector('input.nonstatic-input').value;