实现效果如下所示:
全选状态:
不全选状态:
反选状态:
用jQuery实现以上效果要比js简单的多
不亏是jQuery,写得少做的多
话不多说,直接上代码!!
html:
<div class="wrapper"> <h2>爱好</h2> <hr> <form action="#"> <label><input type="checkbox" id="all">全选</label><br> <label><input type="checkbox" value="游泳">游泳</label> <label><input type="checkbox" value="爬山">爬山</label> <label><input type="checkbox" value="听音乐">听音乐</label> <label><input type="checkbox" value="学web">学web</label> </form> <div>当前选中的爱好:<span></span></div> </div>
复制
css:
.wrapper{ width: 400px; height: 150px; margin: 0 auto; border: 1px solid lightgray; padding: 10px; } .wrapper span { font-weight: 600; }
复制
js:
<script src="./js/jquery-3.6.1.js"></script> <script> // 全选 $("#all").click(function() { var status = $(this).prop("checked"); $("input:not(#all)").prop("checked", status); chText(); }) // 反选 $("input:not(#all)").click(function() { var a = $("input:not(#all)").length; console.log(a); var b = $("input:not(#all):checked").length console.log(b); $("#all").prop("checked", a == b); chText(); }) function chText() { var ary = []; $("input:not(#all):checked").each(function() { ary.push($(this).val()); }) $("span").html(ary); } </script>
复制
html和css没什么可说的,都是非常简单的代码
重中之重就是jQuery部分!!
和js实现的步骤一样,先是实现全选,再是反选,最后创建函数,储存已选中的反选框的值再在全选反选中调用函数。
相对来说,jQuery实现出来更为简单,码字不易,有帮助的请点个赞哦!
以上就是全部内容,更多精彩内容敬请期待,请关注博主学习更多关于前端的知识~