<html> <head> <title>checkbox lab</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script> // chkAll 點擊事件 function checkAll() { var isChecked = $('#chkAll').prop('checked'); // 更新所有 nameCheckbox 的狀態 $('.nameCheckbox').prop('checked', isChecked).trigger('change'); } // 更新 chkAll 狀態 function updateChkAll() { var totalCheckboxes = $('.nameCheckbox').length; var checkedCheckboxes = $('.nameCheckbox:checked').length; var $chkAll = $('#chkAll'); if (checkedCheckboxes === 0) { // 全部未選中 $chkAll.prop('checked', false); $chkAll.removeClass('partial'); } else if (checkedCheckboxes === totalCheckboxes) { // 全部選中 $chkAll.prop('checked', true); $chkAll.removeClass('partial'); } else { // 部分選中 $chkAll.prop('checked', false); // 關鍵修改:部分選中時保持 checked 但變灰色 $chkAll.prop('checked', true).addClass('partial'); } } </script> <style type="text/css"> #chkAll { margin-bottom: 10px; font-size: 10px; } /* 部分選中時的灰色打勾 */ #chkAll.partial { accent-color: gray; /* 現代瀏覽器 */ filter: grayscale(50%) opacity(80%); /* 舊瀏覽器備用 */ } </style> </head> <body> <center> <form name="frmInput" id="frmInput" method="post" action="func.php"> <input type="hidden" name="act" value="input" /> <table border="1"> <tr> <th nowrap="nowrap"><input type="checkbox" id="chkAll" onchange="checkAll()" />全選</th> <th nowrap="nowrap">姓名</th> </tr> <tr> <td><input type="checkbox" class="nameCheckbox" id="chk1" onchange="updateChkAll()" /></td> <td>張三</td> </tr> <tr> <td><input type="checkbox" class="nameCheckbox" id="chk2" onchange="updateChkAll()" /></td> <td>李四</td> </tr> <tr> <td><input type="checkbox" class="nameCheckbox" id="chk3" onchange="updateChkAll()" /></td> <td>王五</td> </tr> </table> </form> </center> </body> </html>
2025-06-08
【jQuery】jQuery + CSS 多個 checkbox 勾選
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言