我有输入:
<input type="number" step="1" min="0" max="4" />
Run Code Online (Sandbox Code Playgroud)
当用户单击向上箭头并且当前值已经是 4 时,如何显示最大值为 4 的警报?
尝试这个
您必须告诉该字段它已经被点击并达到了 4,然后再提醒下次
尊重 max=4 的浏览器将不允许该字段增加超过 4,因此该值本身是不够的
document.getElementById("num").addEventListener("click", function(e) {
const value = this.value,
max = this.getAttribute("max"),
min = this.getAttribute("min"),
minned = this.dataset.minned === "true";
maxed = this.dataset.maxed === "true";
if (value === max && maxed) {
alert("Value is max");
}
if (value === min && minned) {
alert("Value is at 0");
}
this.dataset.maxed = value === max ? "true" : "false";
this.dataset.minned = value === min ? "true" : "false";
})
document.getElementById("num").addEventListener("input", function(e) {
const value = this.value || 0,
min = this.getAttribute("min"),
max = this.getAttribute("max");
if (value != "" && value > max || value < min) {
alert(`Value should be between ${min} and ${max}`);
this.value = "";
}
this.dataset.maxed = value === max ? "true" : "false";
this.dataset.minned = value === min ? "true" : "false";
})
Run Code Online (Sandbox Code Playgroud)
<input id="num" type="number" step="1" min="0" max="4" />
Run Code Online (Sandbox Code Playgroud)