在至少选中三个输入复选框之前,可以通过以下方式隐藏按钮:
// HTML
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
<input type="checkbox" id="checkbox3">
<button id="myButton">按钮</button>
// JavaScript
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");
var myButton = document.getElementById("myButton");
checkbox1.addEventListener("change", hideButton);
checkbox2.addEventListener("change", hideButton);
checkbox3.addEventListener("change", hideButton);
function hideButton() {
var checkedCount = 0;
if (checkbox1.checked) checkedCount++;
if (checkbox2.checked) checkedCount++;
if (checkbox3.checked) checkedCount++;
if (checkedCount >= 3) {
myButton.style.display = "block";
} else {
myButton.style.display = "none";
}
}
<style>
.hidden {
display: none;
}
</style>
<input type="checkbox" id="checkbox1">
<input type="checkbox" id="checkbox2">
<input type="checkbox" id="checkbox3">
<button id="myButton" class="hidden">按钮</button>
<script>
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");
var myButton = document.getElementById("myButton");
checkbox1.addEventListener("change", hideButton);
checkbox2.addEventListener("change", hideButton);
checkbox3.addEventListener("change", hideButton);
function hideButton() {
var checkedCount = 0;
if (checkbox1.checked) checkedCount++;
if (checkbox2.checked) checkedCount++;
if (checkbox3.checked) checkedCount++;
if (checkedCount >= 3) {
myButton.classList.remove("hidden");
} else {
myButton.classList.add("hidden");
}
}
</script>
以上两种方法都可以根据选中的复选框数量来动态隐藏或显示按钮。
领取专属 10元无门槛券
手把手带您无忧上云