近來在給一個公司做考試系統的項目,遇到的問題不少,但其中的幾個讓我對表單的使用頗為感興趣,前端程序員都知道,下拉列表有select標簽,復選框有checkbox,但是兩者合在一起卻少有人去研究,當時接到這樣的要求時我也蒙了,於是去網上查相關資料,查了好久,查不出個結果,只好自己用純html css jq去做一個仿下拉列表中自帶復選框的效果,代碼如下,可直接復制去查看效果,
注:(以下代碼為本人自己編寫,只是一個小Demo,可以直接復制使用,但代碼只是演示其效果和功能,告訴大家如何去寫,所以界面可能沒大家想要的那么漂亮!敬請諒解!0.0.)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{padding: 0;margin: 0;}
#wrap{
width: 500px;
height: 500px;
border: 1px solid blue;
margin: 100px auto;
}
#selectBoard{
width: 300px;
height: 20px;
border: 1px solid black;
border-radius: 5px;
position: relative;
margin: 30px auto;
}
#selectBoard ul{
width: 300px;
background: white;
position: absolute;
top: -10px;
left: -10px;
border: 1px solid red;
border-radius: 5px;
display: none;
}
#selectBoard ul li{
list-style: none;
}
#selectBoard ul li:hover{background: dodgerblue;}
#selectBoard img{
position: absolute;
right: 0;
top: 0;
width: 30px;
}
</style>
</head>
<body>
<div id="wrap">
<div id="selectBoard">
<ul>
<li><input type="checkbox" name="" id="" value="北京" />北京</li>
<li><input type="checkbox" name="" id="" value="上海" />上海</li>
<li><input type="checkbox" name="" id="" value="西安" />西安</li>
<li><input type="checkbox" name="" id="" value="石家庄" />石家庄</li>
</ul>
<span id="shuju"></span>
</div>
</div>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
//定義一個空數組去接收value值
var arr = [];
//仿select的點擊事件
$("#selectBoard").click(function(event){
var ev = event || window.event;
//阻止默認事件及封裝
if (ev.stopPropagation) {
ev.stopPropagation();
}else{
ev.cancelable = true;
}
$("#selectBoard ul").css("display","block");
});
$(window).click(function(){
$("#selectBoard ul").css("display","none");
});
//監聽checkbox的value值 改變則執行下列操作
$("input").change(function(){
if ($(this).prop("checked")) {
arr.push($(this).val()+",");
console.log(arr);
}else{
arr.shift($(this).val()+",");
}
$("#shuju").html(arr);
});
</script>
歡迎大家提出建議!!