JS操作checkbox http://honeyao.iteye.com/blog/238424
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>用图片模拟checkbox三种状态,图片checkbox和checkbox的联动</title> <script language="javascript"> //图片checkbox全选和全不选,控制两个checkbox的函数 function img_cb_choose(elmId, elmCldNm) { var value = document.getElementById(elmId).value; //取出图片的值,通过这个值判断图片CheckBox的三个状态 var checkbox_array = document.getElementsByName(elmCldNm); //取出checkbox数组数 if (value == "default") { //图片checkbox 如果是默认不选,就变成全选 document.getElementById(elmId).src = "images/iconCheckAll.gif"; document.getElementById(elmId).value = "all"; choose(checkbox_array, false, true); } else if (value == "all") { //图片checkbox 如果是全选,就变成不选 document.getElementById(elmId).src = "images/iconUnCheckAll.gif"; document.getElementById(elmId).value = "default"; choose(checkbox_array, true, false); } else if (value == "half") { //图片checkbox 如果是半选,就变成不选 document.getElementById(elmId).src = "images/iconUnCheckAll.gif"; document.getElementById(elmId).value = "default"; choose(checkbox_array, true, false); } } //checkbox 控制图片checkbox function change(elmId, elmCldNm) { var img_checkbox = document.getElementsByName(elmId); var checkbox_array = document.getElementsByName(elmCldNm); //取出checkbox数组 var str_length = 0; //选择checkbox的个数 var checkbox_length = checkbox_array.length; //数组的长度 for (i = 0; i < checkbox_length; i++) { if (checkbox_array[i].checked == true) { str_length++; } } if (str_length == 0) { //默认 全选 document.getElementById(elmId).src = "images/iconUnCheckAll.gif"; document.getElementById(elmId).value = "default"; } else if (str_length < checkbox_length) { //半选状态,点击后变成全不选. document.getElementById(elmId).src = "images/iconCheckGray.gif"; document.getElementById(elmId).value = "half"; } else if (str_length == checkbox_length) { //全不选 document.getElementById(elmId).src = "images/iconCheckAll.gif"; document.getElementById(elmId).value = "all"; } } //传入一个CheckBox,现在的状态,要改变的状态 function choose(checkbox_array, new_status, status) { for (i = 0; i < checkbox_array.length; i++) { //循环所有数组 if (checkbox_array[i].checked == new_status) //现在checkbox的状态 { checkbox_array[i].checked = status; //改变后的状态 } } } </script> </head> <body> <div id="main"> <div id="images_checkbox"> <input id="img_checkbox" name="img_checkbox" type="image" src="images/iconUnCheckAll.gif" onclick="img_cb_choose('img_checkbox','checkbox1');" value="default" /> </div> <div> <input name="checkbox1" type="checkbox" value="1" onclick="change('img_checkbox','checkbox1');" /> <br /> <input name="checkbox1" type="checkbox" value="2" onclick="change('img_checkbox','checkbox1');" /> </div> </div> </body> </html>