checkbox多选框样式改成radio单选框

公司项目有遇到一个需求,需要展示单选框的样式和以往的达成统一的一致,但是要支持多选的功能,于是就有了这样的一出多改单的情况,主要是将checkbox的样式改成radio,既有多选的功能又有单选的样式。

问题:不论是单选还是多选,样式都是无法改变的,我们应该如何实现将checkbox的样式改成radio呢?

思路:我们可以改变其他的样式,比如用一个容器来代替这个checkbox模拟一个radio的样式!checkbox和radio的选中状态都可以通过checked伪类获取到对应的状态,这样实现这个需求就变得简单了。

// 真实的radio
<div class="content-wrap">
    <label><input type="radio" name="test1" id="test1">
        <i>bibi</i>
    </label>
    <label><input type="radio" name="test1" id="test2">
    </label>
</div>

// 由checkbox改造成的radio
<div class="content-wrap">
    <label>
        桃子<input type="checkbox" name="boxTest1" id="boxTest1">
        <i></i>
    </label>
    <label>
        苹果<input type="checkbox" name="boxTest1" id="boxTest2">
        <i></i>
    </label>
    <label>
        香蕉<input type="checkbox" name="boxTest1" id="boxTest3">
        <i></i>
    </label>
</div>
<style>
    .content-wrap{
    
    
        display: flex;
    }
    label{
    
    
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60px;
        padding-right: 15px;
        margin-right: 15px;
        box-sizing: border-box;
    }
    input[type='checkbox']{
    
    
        display: none;
    }
    i{
    
    
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        display: inline-block;
        width: 12px;
        height: 12px;
        background: #fff;
        border: 1px solid #999;
        border-radius: 50%;
    }
    input[type='checkbox']:checked + i::before{
    
    
        content: '';
        display: inline-block;
        position: absolute;
        right: 2px;
        top: 50%;
        transform: translateY(-50%);
        display: inline-block;
        background: #005cc8;
        width: 8px;
        height: 8px;
        border-radius: 50%;
    }
    input[type='checkbox']:checked + i{
    
    
        border: 1px solid #005cc8;
    }
    input[type='radio']:checked + i{
    
    
        color: red;
    }
</style>
<script>
    let checkBoxList = document.querySelectorAll('[name="boxTest1"]');
    let checkedArr = Array(checkBoxList.length);
    for(let i=0; i<checkBoxList.length; i++){
    
    
        checkBoxList[i].onchange = function(){
    
    
            checkedArr[i] = checkBoxList[i].checked;
            // 获取到表单的值
            console.log('checkedArr',checkedArr);
			console.log(`checkBoxList${
      
      i}`,checkBoxList[i].checked);
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/cautionHua/article/details/117295867