1. 程式人生 > >原生態js對單選框的美化並且可複用。

原生態js對單選框的美化並且可複用。

基於純js對單選框的美化,不僅可以設定想設定的顏色,也可以在同一頁面複用多個。還會對程式碼進行詳細的解析,對剛入門的你有一定的幫助哦~

css:

    .radio{
        display:inline-block; 
        width:20px;height:20px;
        border-radius:50%;
        border:1px solid #666;
        margin-right:5px;
        margin-bottom:20px;
        vertical-align:top;
        text-align:center;
        cursor:pointer;
        user-select:none;

    }

   //用偽類的方式在類名radio的後面新增一個標籤,並且內容為:•;注意:內容僅為文字模式,不能為圖片等內容

    .radio.active:after{
        content:"•";
        font-size:30px;
        line-height:20px;
    }
    
html
    <div class="radio-group">
        <label><input type="radio" name="sex" value="男" checked> 男</label>
        <label><input type="radio" name="sex" value="女"> 女</label>
    </div>
    <div class="radio-group">
        <input type="radio" name="xueli" value="本科"> 本科
        <input type="radio" name="xueli" value="大專"> 大專
    </div>

    <div class="radio-group">
        <input type="radio" name="xueli2" value="本科"> 本科
        <input type="radio" name="xueli2" value="大專" checked> 大專
    </div>
js:

//單選框外掛

var radioGroup=document.querySelectorAll('.radio-group');  //獲取瀏覽器中所有的類名為radio-group的檔案。

querySelectorAll:是js中一種方法,查詢多個的意思

radioGroup.forEach(function(group){

    //forEach()方法用於呼叫陣列的每個元素,並將元素傳遞給回撥函式。

   它有三個引數:function(currentValue, index, arr);第一個引數表示的是你當前所觸發事件的元素,這個是必選的;第二個引數是當前元素的索引值,這個是可選的;第三個引數是指當前元素所屬的陣列物件,這個是可選的。


    var radios=group.querySelectorAll('input[type="radio"]');

   //獲取到瀏覽器中所有的型別為radio的檔案。


    radios.forEach(function(radio){

        //隱藏原生態控制元件
        radio.style.display='none';
      //建立一個span元素;

        var span=document.createElement('span');

         span.className='radio'+(radio.checked?' active':'');

        radio.parentNode.insertBefore(span,radio);


        span的點選事件:
        span.onclick=function(){

            //清除所有span的active
            group.querySelectorAll('span.radio').forEach(function(item){
                item.className='radio';
            })

            this.className='radio active';

            radio.checked=true;    
        }
    })

})


做的不好的地方也歡迎廣大前端工程師提意見哦~