我正在嘗試使復選框與 Enter 鍵(當標簽進入時)的行為方式與通常對空格鍵或單擊時的行為相同。我制作了一個確實正在檢查復選框的情況,但是它并沒有像它應該的那樣運行,即我希望它顯示以前隱藏的文本并自行消失。我怎樣才能做到這一點?但是,添加類似的東西document.getElementById("myCheck").click()是行不通的。
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
e.target.checked = !e.target.checked;
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
uj5u.com熱心網友回復:
您需要做的就是觸發click事件,這將選中該框。如果您手動設定checked然后觸發click它將撤消手動設定。
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
//e.target.checked = !e.target.checked;
e.target.click()
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483295.html
標籤:javascript html
上一篇:jQuery按兩個值排序不起作用,只能按第一個值排序
下一篇:添加最后一個parseFloat時JavaScript'calculator'不提供'runningtotal'
