The following is the implementation of selecting/inverting the checkbox using native js. When the checkbox is selected, the effect of selecting all is achieved, and the style changes.
The code is the most concise, js behavior optimized version, just copy and paste.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>复选框全选/反选效果实现</title> <style> body,dl,dt,dd,p{margin:0;padding:0;} body{font-family:Tahoma;font-size:12px;} label,input,a{vertical-align:middle;} label{padding:0 10px 0 5px;} a{color:#09f;text-decoration:none;} a:hover{color:red;} dl{width:120px;margin:10px auto; border-radius:5px;background:#fafafa;} dt{padding-bottom:10px; border-bottom:1px solid #666;} dt label{font-weight:700;} p{margin-top:10px;} </style> </head> <body> <dl> <dt><input type="checkbox" id="checkAll" /><label>全选</label><a href="javascript:;">反选</a></dt> <dd> <p><input type="checkbox" name="item" /><label>选项(一)</label></p> <p><input type="checkbox" name="item" /><label>选项(二)</label></p> <p><input type="checkbox" name="item" /><label>选项(三)</label></p> <p><input type="checkbox" name="item" /><label>选项(四)</label></p> <p><input type="checkbox" name="item" /><label>选项(五)</label></p> <p><input type="checkbox" name="item" /><label>选项(六)</label></p> <p><input type="checkbox" name="item" /><label>选项(七)</label></p> <p><input type="checkbox" name="item" /><label>选项(八)</label></p> <p><input type="checkbox" name="item" /><label>选项(九)</label></p> <p><input type="checkbox" name="item" /><label>选项(十)</label></p> </dd> </dl> <script type="text/javascript"> (function(){ var aInput = document.getElementsByTagName("input"); var aBack = document.getElementsByTagName("a")[0]; var aLabel = document.getElementsByTagName("label")[0]; var allInput = aInput[0]; //全选设置,当点击事件发生时候,如果被选择全部选中,并且文本内容改变 allInput.onclick=function(){ if(aInput[0].checked){ for(var i=1;i<aInput.length;i++){ aInput[i].checked = true; } aLabel.innerHTML = "全不选"; } else{ for(var i=1;i<aInput.length;i++){ aInput[i].checked = false; } aLabel.innerHTML = "全选"; } } //反选设置,选中的内容是原本内容的取反 aBack.onclick=function(){ for(var i=1;i<aInput.length;i++){ aInput[i].checked = !aInput[i].checked; } } })(); </script> </body> </html>
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
Please pay attention to the PHP Chinese website for more articles related to javascript implementation of selecting all or inverting check boxes!