1. 程式人生 > >layui複選框

layui複選框

效果圖

 

layui複選框,一個主的複選框控制多個從複選框,主複選框和從複選框的顏色不一樣

 

layui複選框的樣式,都是在選然後才會有的,所以直接通過css設定就實現不了了。只可以通過js動態設定

 

html程式碼使用了jfinal的模板

<div class="layui-inline">
              <label class="layui-form-label"><font class="faiqi-font-red-star">*</font>#(i18n.get('所屬校區'))</
label> <div class="layui-input-block"> <input id="qx" lay-filter="allCheck" type="checkbox" value="" name="" title="#(i18n.get('全選'))" > #for(campus : campusList) <input type="checkbox" lay-filter="campus" class
="campus" value="#(campus.id)" name="campusIds[#(campus.id)]" title="#(campus.campusName)" #(campusIdStr.contains(',' + campus.id + ',') ? 'checked="checked"':'')> #end </div> </div>

layui程式碼

$(function(){

layui.use('form', function(){
	var form = layui.form;
	form.on("checkbox(allCheck)", function(data){
		console.log(data);
		console.log(data.elem.checked);
		if (data.elem.checked) {
		    //動態設定全選按鈕顏色,不可以這裡設定,這裡設定後,前端選然後不會有效果的,
			//猜測原因是,form.render("checkbox"); 導致的,設定後layui又渲染了,把我自己設定的顏色覆蓋了。所以設定需要在渲染後再設定,就等於是用我的css覆蓋了layui的css
			$(".campus").each(function(){
				$(this).prop('checked', true);
			});
		} else {
			$(".campus").each(function(){
				$(this).prop('checked',  false);
			});
		}
		form.render("checkbox");
       //渲染後設置我的顏色
		allCheckbox();
	});

    //檢視是否被全選了,全選了,全選按鈕編輯的時候就是被選中中狀態
    function initselect(){
        let allSelect = true;
        $(".campus").each(function(index, elem){
            //每個checkbox新增點選事件,如果點選了,使得所有的按鈕中出現了不被選中的,那麼全選按鈕就不被選中
            if($(this).prop('checked') == false){
                allSelect = false;
            }
        });
        console.log("是否全選",allSelect)
        $("#qx").prop('checked',allSelect);
        form.render("checkbox");
        //記得把設定事件放到渲染事件後
        allCheckbox();
    }
    initselect();

    //校區點選事件,如果有校區沒有被選中,那麼全選按鈕就不能夠顯示選中狀態
    form.on("checkbox(campus)", function(data){
        let checked = data.elem.checked;
        initselect();
	});

});

	//全選按鈕和其他按鈕的顏色不一樣
	function allCheckbox(){
		qx1=$('#qx').next('div').children('span');
		if($('#qx').prop('checked')){
		    //被選中就設定顏色
            qx1.css({
                'background-color':'#e4393c'
            })
		}
	}
	//初始化設定全選按鈕的顏色,
	allCheckbox();

})

  css

<style>
.layui-form-checkbox span {
   		width:154px
	}
.layui-unselect.layui-form-checkbox{
		margin-bottom:5px;
	}
	.layui-form-checkbox span{
		color:#4C5277;
	}
	.layui-form-checked span{
		color:#fff;
	}
	/*.layui-form-checked span{
		background-color:#b31717!important;
	}*/

</style>