zoukankan      html  css  js  c++  java
  • 自定义单选,多选按钮

    html:
    <div data-toggle="buttons" style="margin-bottom:30px;">
    <a style="position: relative" class="mybtn">
    <span>男</span>
    <input type="radio" name="sex1" style="position: absolute">
    </a>
    <a style="position: relative" class="mybtn">
    <span>女</span>
    <input type="radio" name="sex1" style="position: absolute">
    </a>
    </div>

    <div data-toggle="buttons">
    <a style="position: relative" class="mybtn">
    <span>喜欢打球</span>
    <input type="checkbox" name="sex2" style="position: absolute">
    </a>
    <a style="position: relative" class="mybtn">
    <span>喜欢看书</span>
    <input type="checkbox" name="sex2" style="position: absolute">
    </a>
    <a style="position: relative" class="mybtn">
    <span>喜欢画画</span>
    <input type="checkbox" name="sex2" style="position: absolute">
    </a>
    <a style="position: relative" class="mybtn">
    <span>喜欢摄影</span>
    <input type="checkbox" name="sex2" style="position: absolute">
    </a>
    </div>
    css:
    .mybtn{
    background: #ebebeb;
    padding: 5px 10px;
    color: #333;
    border-radius: 6px;
    border:1px solid #ddd;
    margin:0px 5px;
    cursor: pointer;
    }
    .mybtn input{
    visibility: hidden;
    position: absolute;
    }
    .mybtn.active{
    background: #59a2ff;
    color: #fff;
    }
    jquery:
    +(function($){
    var Button = function(element){
    this.$element = element;
    }
    Button.prototype.toggle = function(){
    $parents = this.$element.parents('[data-toggle="buttons"]');
    if($parents.find('[type="radio"]').length>0){
    //单选
    $parents.find(".active").removeClass("active");
    this.$element.addClass("active");
    this.radioChecked();
    }else {
    //多选
    this.$element.toggleClass("active");
    this.checkboxChecked();
    }
    }
    Button.prototype.radioChecked = function(){
    var $radio = this.$element.find('[type="radio"]');
    $radio.prop("checked",true);
    }
    Button.prototype.checkboxChecked = function(){
    var $checkbox = this.$element.find('[type="checkbox"]');
    if(this.$element.hasClass("active")){
    $checkbox.prop("checked",false);
    }else{
    $checkbox.prop("checked",true);
    }
    }
    $(function () {
    $(document).on("click",'[data-toggle="buttons"]',function (e) {
    var $btn = $(e.target);
    //若点击到的是内部的span,委托,参考jQuery API:http://jquery.cuishifeng.cn/closest.html
    if (!$btn.hasClass('mybtn')) $btn = $btn.closest('.mybtn')
    new Button($btn).toggle();
    })
    })
    })(jQuery);



  • 相关阅读:
    【流水账】2021-06-19 Day-09
    【流水账】2021-06-18 Day-08
    【流水账】2021-06-16 Day-06
    【流水账】2021-06-15 Day-05
    .Net调用Java的实现方法
    优先队列的实例题
    栈的相关程序题
    重载函数
    卡特兰数
    关于全排列的递归
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/9856376.html
Copyright © 2011-2022 走看看