用js写出一个漂亮的单选框选中效果

一般的input框比较简单,我们可以用JavaScript配合css背景图片定位让我们模拟写出一个点击选中效果

首先需要有个图片素材,当页面加载的时候是背景图片定位到左图,当我们点击图片的时候,背景图片定位到右图

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/jquery.js"></script>
        <style type="text/css">
            
            
        .check_box{
            height: 20px;
            width: 20px;
            display: block;
        
            background: url("images/shop-icon.png") no-repeat;
            background-size: 50px 100px;
        }
        /*属性选择器*/
        .check_box[checked]{
            background-position: -25px 0;
        }
        </style>
    </head>
    <body>        
            <span class="check_box"></span>
  
        <script type="text/javascript">
            var checkBtn = document.getElementsByClassName('check_box');
            for(var j = 0 ; j < checkBtn.length; j++){
                checkBtn[j].onclick = function(){
                    var hasChecked = this.getAttribute('checked');
                    if(hasChecked !== null){
                        this.removeAttribute('checked');
                    }else{
                        this.setAttribute('checked',' ');
                    }
                }
            }
        </script>

    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/shangrao/p/12814441.html