<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="css/fSelect.css" /> </head> <body> <div class="select" style="display: inline-block;position: relative;"> <input type="text" class="ipt" name=""/> <div class="check hide" style="width: 260px;border: 2px solid #000;position: absolute;top: 21px;left: 0;padding: 0 10px;"> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项1</label></p> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项2</label></p> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项3</label></p> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项4</label></p> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项5</label></p> <p style="display: inline-block;"><input type="checkbox" class="chk" name="item"><label>选项6</label></p> <br/><button class="chkAll">全选</button> <button class="clearAll">清空</button> </div> </div> </body> <script type="text/javascript" src="js/jquery-2.1.0.js" ></script> <script> $(document).on("click", ".chk" ,function(){ var array = []; $(".chk:checked").each(function () { if(!contains(array, $(this).next().html())){ array.push($(this).next().html()); } }) $(‘.ipt‘).val(array.toString()) console.log(array,44444) }) var check = function(){ var array = []; $(".chk:checked").each(function () { if(!contains(array, $(this).next().html())){ array.push($(this).next().html()); } }) $(‘.ipt‘).val(array.toString()) } $(‘.chkAll‘).click(function(){ $(".chk:checkbox").prop("checked",true); check(); }) $(‘.clearAll‘).click(function(){ $(".chk:checkbox").prop("checked",false); check(); }) $(‘.ipt‘).click(function(){ $(‘.check‘).toggleClass(‘hide‘); }) document.onmouseup = function(e){ var e = e || window.event; var target = e.target || e.srcElement; var _con = $(‘.select‘)//获取你的目标元素 //1. 点击事件的对象不是目标区域本身 //2. 事件对象同时也不是目标区域的子元素 if(!_con.is(e.target) && _con.has(e.target).length === 0){ $(‘.check‘).addClass(‘hide‘); } } function contains(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) { return true; } } return false; } </script> </html>
原文:https://www.cnblogs.com/lxqboke/p/11322629.html