【问题标题】:Styling checkboxes with jQuery使用 jQuery 设置复选框样式
【发布时间】:2013-06-09 13:02:55
【问题描述】:

我需要通过 jquery 对一些复选框进行样式化,但我不想使用插件。我只需要一个简单的 jQuery 代码。

我想使用一个带有 css 样式的简单列表。

<ul id="list">
 <li class="selected"><a id="1" href="#">1</a></li>
 <li><a id="2" href="#">2</a></li>
 <li><a id="3" href="#">3</a></li>
</ul>

同时我在代码中加入了被 css 隐藏的输入复选框:

<input type="checkbox" id="1" name="rivista_numero" value="1" checked />    
<input type="checkbox" id="2" name="rivista_numero" value="2" />
<input type="checkbox" id="3" name="rivista_numero" value="3" />

如果我点击“链接”,则使用 jquery,父 li 元素将收到“选定”类,并且具有相同 ID 的复选框将被选中。

您认为这可能是一个好的解决方案吗?有没有可能用 jQuery 实现这个结果?

【问题讨论】:

  • 不,这不是一个好的解决方案,因为 ID 不仅应该是唯一的,而且使用数字作为 ID 也是不好的做法,并且会给您带来问题。
  • 我根本不会使用 js 来设置复选框的样式,而是使用 css:stackoverflow.com/a/4148544/1960455
  • ID 是唯一的。也许您可以将它们定义为类?
  • 一次只能勾选一个复选框吗?我想这就是你想要的 - 单选按钮会更好。
  • 所以,@JP-Hellemons 的回答是完全正确的。无需 javascript - 只需 CSS。

标签: jquery input checkbox radio


【解决方案1】:

无需 javascript,只需 CSS http://jsfiddle.net/jphellemons/XvZY9/

HTML:

<input type="checkbox" id="c1" name="cc" />
<label for="c1"><span></span>Check Box 1</label>
<br/>
<input type="checkbox" id="c2" name="cc" />
<label for="c2"><span></span>Check Box 2</label>

CSS:

input[type="checkbox"] {
    display:none;
}
input[type="checkbox"] + label {
    color:#000;
    font-family:Arial, sans-serif;
    font-size:14px;
}
input[type="checkbox"] + label span {
    display:inline-block;
    width:19px;
    height:19px;
    margin:-1px 4px 0 0;
    vertical-align:middle;
    background:url(http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/check_radio_sheet.png) left top no-repeat;
    cursor:pointer;
}
input[type="checkbox"]:checked + label span {
    background:url(http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/check_radio_sheet.png) -19px top no-repeat;
}

对于单选按钮 http://jsfiddle.net/jphellemons/XvZY9/1/

来源:http://webdesigntutsplus.s3.amazonaws.com/tuts/391_checkboxes/demo.html

【讨论】:

  • 我相信他想要radiobutton 行为而不是不正确地选择checkbox。 '使用jquery,如果我点击'链接,父li元素将收到'selected'类,具有相同类的旧li元素会丢失它,并且将选中具有相同ID的复选框。'
  • @ElmoVanKielmo 你可能是对的,那么 Pennywise83 应该使用教程中的无线电部分:webdesign.tutsplus.com/tutorials/htmlcss-tutorials/…
  • @Pennywise83 编辑了他的要求,所以你的第一个答案很好。
  • 只是想指出在输入中设置display: none 将使在表单的那部分进行的制表符无效。更好的选择是opacity: 0,然后设置:focus 样式
【解决方案2】:

你可以使用这个插件,

var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";


/* No need to change anything after this */


document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
    init: function() {
        var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
        for(a = 0; a < inputs.length; a++) {
            if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                span[a] = document.createElement("span");
                span[a].className = inputs[a].type;

                if(inputs[a].checked == true) {
                    if(inputs[a].type == "checkbox") {
                        position = "0 -" + (checkboxHeight*2) + "px";
                        span[a].style.backgroundPosition = position;
                    } else {
                        position = "0 -" + (radioHeight*2) + "px";
                        span[a].style.backgroundPosition = position;
                    }
                }
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                inputs[a].onchange = Custom.clear;
                if(!inputs[a].getAttribute("disabled")) {
                    span[a].onmousedown = Custom.pushed;
                    span[a].onmouseup = Custom.check;
                } else {
                    span[a].className = span[a].className += " disabled";
                }
            }
        }
        inputs = document.getElementsByTagName("select");
        for(a = 0; a < inputs.length; a++) {
            if(inputs[a].className == "styled") {
                option = inputs[a].getElementsByTagName("option");
                active = option[0].childNodes[0].nodeValue;
                textnode = document.createTextNode(active);
                for(b = 0; b < option.length; b++) {
                    if(option[b].selected == true) {
                        textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                    }
                }
                span[a] = document.createElement("span");
                span[a].className = "select";
                span[a].id = "select" + inputs[a].name;
                span[a].appendChild(textnode);
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                if(!inputs[a].getAttribute("disabled")) {
                    inputs[a].onchange = Custom.choose;
                } else {
                    inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                }
            }
        }
        document.onmouseup = Custom.clear;
    },
    pushed: function() {
        element = this.nextSibling;
        if(element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
        } else if(element.checked == true && element.type == "radio") {
            this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
        } else if(element.checked != true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
        } else {
            this.style.backgroundPosition = "0 -" + radioHeight + "px";
        }
    },
    check: function() {
        element = this.nextSibling;
        if(element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 0";
            element.checked = false;
        } else {
            if(element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
            } else {
                this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
                group = this.nextSibling.name;
                inputs = document.getElementsByTagName("input");
                for(a = 0; a < inputs.length; a++) {
                    if(inputs[a].name == group && inputs[a] != this.nextSibling) {
                        inputs[a].previousSibling.style.backgroundPosition = "0 0";
                    }
                }
            }
            element.checked = true;
        }
    },
    clear: function() {
        inputs = document.getElementsByTagName("input");
        for(var b = 0; b < inputs.length; b++) {
            if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
            } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
            } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            }
        }
    },
    choose: function() {
        option = this.getElementsByTagName("option");
        for(d = 0; d < option.length; d++) {
            if(option[d].selected == true) {
                document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
            }
        }
    }
}
window.onload = Custom.init;

来自http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/

演示在这里http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/example/

【讨论】:

    【解决方案3】:

    我能想到的最简单的方法:

    var setupCheckboxes = function() {
        // Checkbox Styling
        $('input[type=checkbox]').each(function() {
            var $this = $(this);
            $this.addClass('checkbox');
            $('<span class="checkbox"></span>').insertAfter($this);
            if ($this.is(':checked')) {
                $this.next('span.checkbox').addClass('on');
            };
            $this.fadeTo(0,0);
            $this.change(function(){
                $this.next('span.checkbox').toggleClass('on');
            });
        });
    };
    setupCheckboxes();
    

    然后在css中

    .checkbox {
        position: relative;
        z-index: 10;
    }
    
    span.checkbox {
        z-index: 5;
        display: inline-block;
        width: 15px;
        height: 15px;
        background: #fff;
        border: 1px solid #000;
        margin: 1px 0 0 -14px;
        top: 3px;
        float: left;
        &.on {
            background: $blue;
        }
    }
    

    【讨论】:

      【解决方案4】:

      HTML 复选框的样式不能太多,因此最好自己制作 ;)
      我为自己做了一个,它不使用任何图像,只使用纯 CSS。因此,它具有可扩展性和可定制性。

      获取复选框$('#id_of_my_custom_checkbox').val()的值 -> true/false

      这是工作小提琴:https://jsfiddle.net/JerryGoyal/xr62yara/8/

      HTML:

      <div>
      
                  <div id='mycheckbox' class='custom-checkbox'>
                      <div class='custom-tick'></div>
                  </div>
      
                  <span>I agree</span>
      
              </div>
      

      CSS

      .custom-checkbox{
          border: solid 2px orange;
          height: 15px;
          width: 15px;
          display: inline-block;
          cursor: pointer;
          -webkit-user-select: none;
      -khtml-user-select: none;
      -moz-user-select: none;
      -o-user-select: none;
      user-select: none;
        }
      .custom-tick{
          border: inherit;
          display: inherit;
          cursor: inherit;
          visibility: hidden;
          height: 8px;
          width: 5px;
          transform: rotate(45deg);
          border-left: 0;
          border-top: 0;
          border-width: 2px;
          margin: 0px 0px 3px 4px;
      }
      

      JS:

      $(document).ready(function () {
          $('.custom-checkbox').click(function (e) {
              toggleCustomCheckbox(e.target);
          })
      });
      
      function toggleCustomCheckbox(el) {
          var tickEl = $(el).find('.custom-tick').addBack('.custom-tick');
          if (tickEl.css('visibility') === 'hidden') {
              tickEl.css('visibility', 'visible')
              $('.custom-checkbox').val(true)
              alert('you ticked me')
          } else {
              tickEl.css('visibility', 'hidden')
              $('.custom-checkbox').val(false)
              alert('you un-ticked me')
          }
      
      }
      function setCustomCheckbox(checkboxid, val) {
          var tickEl = $(checkboxid).find('.custom-tick').addBack('.custom-tick');
          if (val && val === true) {
              tickEl.css('visibility', 'visible')
              $('.custom-checkbox').val(true)
          }
          else {
              tickEl.css('visibility', 'hidden')
              $('.custom-checkbox').val(false)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        • 2016-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多