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);



  • 相关阅读:
    iframe,modaldialog父子窗口相互通信的问题
    bootstrap基础知识
    基于原生js的图片延迟加载
    通过原生js的ajax或jquery的ajax获取服务器的时间
    转 fiddler教程
    正则表达式
    es6 对象
    ES6
    axios
    javascript闭包和闭包的几种写法和用法
  • 原文地址:https://www.cnblogs.com/yuyedaocao/p/9856376.html
Copyright © 2011-2022 走看看