<style> td,table{border:1px solid #323841;} </style> <form method="get" action=""> <table> <tr> <td>测试一下</td> <td>测试一下</td> </tr> <tr> <td>测试</td> <td><input class="kaiguan" name="kaiguan1" value="0"></td> </tr> <tr> <td>测试</td> <td><input class="kaiguan" name="kaiguan2" value="1"></td> </tr> <tr> <td>测试</td> <td><input class="kaiguan" name="kaiguan3" value="0"></td> </tr> <tr> <td>测试</td> <td><input class="kaiguan" name="kaiguan4" value="0"></td> </tr> <tr> <td>测试</td> <td><input class="kaiguan" name="kaiguan5" value="1"></td> </tr> <tr> <td></td> <td><input type="submit"></td> </tr> </table> </form> <script> //需要开关按钮直接在页面写 <input class="kaiguan"> 就行了 inputArr=document.querySelectorAll("input[class='kaiguan']"); spanArr=new Array(); iArr=new Array(); for (i=0; i<inputArr.length; i++){ spanArr[i]=document.createElement('span'); spanArr[i].i=i; spanArr[i].style="display:inline-block;outline: none;appearance: none;-webkit-appearance: none;-moz-appearance: none;position: relative;width: 50px;height: 25px;background: #ccc;border-radius: 15px;transition: border-color .3s, background-color.3s;cursor:pointer;"; inputArr[i].parentNode.appendChild(spanArr[i]); iArr[i]=document.createElement('i'); iArr[i].style="display: inline-block;width:20px;height:20px;border-radius: 50%;background: #fff;box-shadow: 0, 0, 2px, #999;transition: .1s;top: 2px;position: absolute;left: 2px;"; spanArr[i].appendChild(iArr[i]); spanArr[i].onclick=function(){ if(inputArr[this.i].value=="1"){ inputArr[this.i].value="0"; spanArr[this.i].style.background="#ccc"; iArr[this.i].style.left="2px"; }else{ inputArr[this.i].value="1"; iArr[this.i].style.left="55%"; spanArr[this.i].style.background="#3a6ea5"; } } //加载后立即显示 if(inputArr[i].value=="1"){ iArr[i].style.left="55%"; spanArr[i].style.background="#3a6ea5"; }else{ spanArr[i].style.background="#ccc"; iArr[i].style.left="2px"; } inputArr[i].style.display="none"; } </script> </body> </html>