[英]How can I toggle the visibility of a div when a checkbox is checked with CSS?
我已經嘗試了幾種方法來做到這一點,包括通過 javascript,但我無法弄清楚。 我有一個表,header 包含一個“全選”復選框,每個條目都有一個復選框。
適用html:
<table>
<thread>
<tr>
<th class="border-top-0"><input type="checkbox" id="selectAll" value="selectAll"></th>
</tr>
</thread>
<tbody>
<td>
<%= check_box_tag "contacts[]", contact.id %>
</td>
理想情況下,我希望在選中任何復選框時顯示一個隱藏的 div。 我通過 Javascript 部分地能夠完成這個:
var checkboxes = document.querySelectorAll('input#contacts_');
//var selectAll = document.querySelector('input#selectAll');
var checkCount = 0;
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
checkbox.checked ? checkCount++ : checkCount--;
checkCount > 0 ? actionsContainer.style.opacity = '1': actionsContainer.style.opacity = '0';
console.log(checkCount)
});
});
但是,當檢查“選擇所有”復選框時,其他復選框未注冊為被檢查,除非未選擇聯系然后重新選擇聯系人,否則我將無法顯示隱藏的div。 我還嘗試向selectAll
變量添加一個單獨的事件偵聽器,但結果一團糟。
所以我正在嘗試 CSS 解決方案:
input[type='checkbox']:checked.mobile-actions {
opacity: 1;
}
計算如果每個復選框都是input[type="checkbox"]
它們都會被觸摸並且移動操作 div 會顯示。 但這似乎也不起作用。 我怎樣才能完成這個?
在表<table class='items'>
添加一個 class
為點擊整個 class 創建事件偵聽器,並根據點擊的項目處理它。 例如:
const itemsTable = document.querySelector('.items'); const items = document.querySelectorAll('.item'); // Class of each item itemsTable.addEventListener('click', (e) => { const traget = e.target.className; if(target === 'selectAll') { for(const n of items) { if(n.parentNode.parentNode.hidden === true) n.parentNode.parentNode.hidden = false; if(n.checked === true) console.log('I am checked'); if(n.checked === false) console.log('I am unchecked'); } } if(target === 'item') { /// Do something } }
以同樣的方式在這個監聽器中你可以監聽單個項目的點擊,所以你不需要為每個項目單獨添加事件監聽器。
在您選中/取消選中某個項目的同時,您可以更改其樣式以隱藏它或任何您想要的東西。
我終於能夠通過 Javascript 解決問題:
document.addEventListener('change', function() {
arr = [];
checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (i = checkboxes.length -1; i >= 0; i--) {
if (checkboxes[i].checked) {
arr.push(checkboxes[i].value);
}
}
arr.length > 0 ? actionsContainer.style.opacity = '1' : actionsContainer.style.opacity = '0'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.