我尝试使用“:in-range” CSS 伪类,我创建了一个没有值的数字类型的输入,我假设该输入没有值,所以它应该是无效的或超出范围,但它选择“:范围内”,这是正确的行为吗?我还使用 JQuery 选择输入,它显示输入为空字符串,我认为空字符串不应介于我在代码中编写的 5 到 10 之间。你对使用“:in-range”输入没有值的建议是什么。
$(function(){
$("#showVal").click(function(){
let val = $("#input").val();
alert(val);
});
});
input[type="number"]:out-of-range{
background-color:red;
}
input[type="number"]:in-range{
background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" type="number" min="5" max="10"/>
<button id="showVal">Show Value</button>
最佳答案
出于某种原因,:out-of-range
不适用于空输入。
我的建议是也添加 :invalid
伪类。
The :invalid CSS pseudo-class represents any or other element whose contents fail to validate.
但是输入必须设置为required。
然后,如果输入为空,它将被视为无效,并且可以应用 :out-of-range
的相同 CSS。
input[type="number"]:invalid{
background-color:red;
}
<input id="input" type="number" min="5" max="10" required />
关于html - 为什么:in-range select input that has not value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059309/