我试图使用以下样式的复选框:

<输入类型=“checkbox”样式=“border:2px点数:00f;显示:block;背景:ff0000;”/>

但是没有应用样式。复选框仍然显示其默认样式。我如何给它指定的样式?


当前回答

不,你仍然不能设置复选框本身的样式,但我(最终)想出了如何在保持单击复选框的功能的同时设置一个错觉的样式。这意味着即使光标不是完全静止,你也可以切换它,而不用冒险选择文本或触发拖放!

这个解决方案可能也适用于单选按钮。

以下内容在ie9、Firefox 30.0和Chrome 40.0.2214.91中都可以使用,这只是一个基本示例。您仍然可以将它与背景图像和伪元素结合使用。

http://jsfiddle.net/o0xo13yL/1/

label {
    display: inline-block;
    position: relative; /* Needed for checkbox absolute positioning */
    background-color: #eee;
    padding: .5rem;
    border: 1px solid #000;
    border-radius: .375rem;
    font-family: "Courier New";
    font-size: 1rem;
    line-height: 1rem;
}

label > input[type="checkbox"] {
    display: block;
    position: absolute; /* Remove it from the flow */
    width: 100%;
    height: 100%;
    margin: -.5rem; /* Negative the padding of label to cover the "button" */
    cursor: pointer;
    opacity: 0; /* Make it transparent */
    z-index: 666; /* Place it on top of everything else */
}

label > input[type="checkbox"] + span {
    display: inline-block;
    width: 1rem;
    height: 1rem;
    border: 1px solid #000;
    margin-right: .5rem;
}

label > input[type="checkbox"]:checked + span {
    background-color: #666;
}

<label>
    <input type="checkbox" />
    <span>&nbsp;</span>Label text
</label>

其他回答

呵!所有这些变通方法让我得出结论,如果你想要设置HTML复选框的样式,那么它就很糟糕。

作为一个警告,这不是一个CSS实现。我只是想分享一下我想出的解决办法以防其他人会觉得有用。


我使用HTML5 canvas元素。

这样做的好处是您不必使用外部图像,并且可能节省一些带宽。

缺点是,如果浏览器由于某种原因不能正确地呈现它,那么就没有退路了。不过,在2017年,这是否仍然是一个值得商榷的问题。

更新

我发现旧的代码很难看,所以我决定重写一遍。

Object.prototype.create = function(args){
    var retobj = Object.create(this);

    retobj.constructor(args || null);

    return retobj;
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = !self.state;
            self.draw();
        }
    },

    draw_rect: function(color, offset){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offset, offset,
                this.width - offset * 2, this.height - offset * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0);
        this.draw_rect("#FFFFFF", 1);

        if(this.is_checked())
            this.draw_rect("#000000", 2);
    },

    is_checked: function(){
        return !!this.state;
    }
});

这里是一个工作演示。

新版本使用原型和差分继承来创建一个用于创建复选框的高效系统。创建复选框:

var my_checkbox = Checkbox.create();

这将立即将复选框添加到DOM并连接事件。查询复选框是否勾选。

my_checkbox.is_checked(); // True if checked, else false

同样需要注意的是,我去掉了循环。

更新2

在上次更新中我忽略了一点,那就是使用canvas比仅仅创建一个你想要的复选框有更多的优势。如果您愿意,还可以创建多状态复选框。

Object.prototype.create = function(args){
    var retobj = Object.create(this);

    retobj.constructor(args || null);

    return retobj;
}

Object.prototype.extend = function(newobj){
    var oldobj = Object.create(this);

    for(prop in newobj)
        oldobj[prop] = newobj[prop];

    return Object.seal(oldobj);
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = !self.state;
            self.draw();
        }
    },

    draw_rect: function(color, offsetx, offsety){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offsetx, offsety,
                this.width - offsetx * 2, this.height - offsety * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0, 0);
        this.draw_rect("#FFFFFF", 1, 1);
        this.draw_state();
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);
    },

    is_checked: function(){
        return this.state == 1;
    }
});

var Checkbox3 = Checkbox.extend({
    ev_click: function(self){
        return function(unused){
            self.state = (self.state + 1) % 3;
            self.draw();
        }
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);

        if(this.is_partial())
            this.draw_rect("#000000", 2, (this.height - 2) / 2);
    },

    is_partial: function(){
        return this.state == 2;
    }
});

我稍微修改了上一个代码片段中使用的复选框,使其更通用,从而可以使用具有3个状态的复选框“扩展”它。这是一个演示。正如您所看到的,它已经拥有了比内置复选框更多的功能。

在JavaScript和CSS之间进行选择时需要考虑的问题。

旧的、设计糟糕的代码

演示工作

首先,设置一个画布

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    checked = 0; // The state of the checkbox
canvas.width = canvas.height = 15; // Set the width and height of the canvas
document.body.appendChild(canvas);
document.body.appendChild(document.createTextNode(' Togglable Option'));

接下来,设计一种让画布自我更新的方法。

(function loop(){
  // Draws a border
  ctx.fillStyle = '#ccc';
  ctx.fillRect(0,0,15,15);
  ctx.fillStyle = '#fff';
  ctx.fillRect(1, 1, 13, 13);
  // Fills in canvas if checked
  if(checked){
    ctx.fillStyle = '#000';
    ctx.fillRect(2, 2, 11, 11);
  }
  setTimeout(loop, 1000/10); // Refresh 10 times per second
})();

最后一部分是使其具有互动性。幸运的是,这很简单:

canvas.onclick = function(){
  checked = !checked;
}

这就是你在IE中可能会遇到的问题,因为JavaScript中奇怪的事件处理模型。


我希望这能帮助到一些人;它绝对符合我的需要。

现代无障碍解决方案-使用重音颜色

使用新的重音-颜色属性,并确保满足适当的3:1对比度,以确保可访问性。这也适用于单选按钮。

.red-input { 颜色:# 9 d3039; 高度:20 px;/*不需要*/ 宽度:20 px;/*不需要*/ } <input class="red-input" type="checkbox" /> <!—单选按钮示例—> <input class="red-input" type="radio" />


旧的答案,我只建议如果你需要更多的定制比上述提供:

我一直在翻看这些答案,大量的答案只是将可访问性排除在门外,并以多种方式违反WCAG。我添加了单选按钮,因为大多数情况下,当你使用自定义复选框时,你也需要自定义单选按钮。

小提琴:

复选框-纯CSS -免费的第三方库 单选按钮-纯CSS -免费的第三方库 复选框*使用FontAwesome,但可以很容易地与Glyphicons等交换

虽然迟到了,但不知何故,在2019年、2020年和2021年,这仍然很困难,所以我添加了我的三个解决方案,它们易于使用和使用。

这些都是免费的JavaScript,可访问的,和外部库免费*…

如果你想要即插即用,只要复制样式表从fiddles,编辑CSS中的颜色代码,以适应你的需要,并在你的方式。如果需要,可以为复选框添加自定义svg复选标记图标。我为那些不喜欢css的人添加了很多注释。

如果你有很长的文本或一个小的容器,并且在复选框或单选按钮输入下遇到文本换行,那么就像这样转换为div。

更详细的解释: 我需要一个解决方案,不违反WCAG,不依赖于JavaScript或外部库,不打破键盘导航,如标签或空格键选择,允许焦点事件,一个解决方案,允许禁用复选框,既选中和未选中,最后一个解决方案,我可以自定义的复选框的外观,但我想与不同的背景颜色,边界半径,svg背景等。

我结合了@Jan turoironic的回答,想出了我自己的解决方案,看起来效果不错。我已经做了一个单选按钮小提琴,使用了许多相同的代码从复选框,以使此工作与单选按钮。

我仍然在学习无障碍,所以如果我错过了一些东西,请留下评论,我会尽量纠正它。

这是我的复选框的代码示例:

input[type="checkbox"] { position: absolute; opacity: 0; z-index: -1; } /* Text color for the label */ input[type="checkbox"]+span { cursor: pointer; font: 16px sans-serif; color: black; } /* Checkbox un-checked style */ input[type="checkbox"]+span:before { content: ''; border: 1px solid grey; border-radius: 3px; display: inline-block; width: 16px; height: 16px; margin-right: 0.5em; margin-top: 0.5em; vertical-align: -2px; } /* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */ input[type="checkbox"]:checked+span:before { /* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */ background-image: url('https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/collection/build/ionicons/svg/ios-checkmark.svg'); background-repeat: no-repeat; background-position: center; /* The size of the checkmark icon, you may/may not need this */ background-size: 25px; border-radius: 2px; background-color: #e7ffba; color: white; } /* Adding a dotted border around the active tabbed-into checkbox */ input[type="checkbox"]:focus+span:before, input[type="checkbox"]:not(:disabled)+span:hover:before { /* Visible in the full-color space */ box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1); /* Visible in Windows high-contrast themes box-shadow will be hidden in these modes and transparency will not be hidden in high-contrast thus box-shadow will not show but the outline will providing accessibility */ outline-color: transparent; /*switch to transparent*/ outline-width: 2px; outline-style: dotted; } /* Disabled checkbox styles */ input[type="checkbox"]:disabled+span { cursor: default; color: black; opacity: 0.5; } /* Styles specific to this fiddle that you do not need */ body { padding: 1em; } h1 { font-size: 18px; } <h1> NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn </h1> <p>You can easily change the background color, checkbox symbol, border-radius, etc.</p> <label> <input type="checkbox"> <span>Try using tab and space</span> </label> <br> <label> <input type="checkbox" checked disabled> <span>Disabled Checked Checkbox</span> </label> <br> <label> <input type="checkbox" disabled> <span>Disabled Checkbox</span> </label> <br> <label> <input type="checkbox"> <span>Normal Checkbox</span> </label> <br> <label> <input type="checkbox"> <span>Another Normal Checkbox</span> </label>

通过使用:after和:before伪类附带的新功能,可以实现相当酷的自定义复选框效果。这样做的好处是:您不需要向DOM添加任何其他内容,只需添加标准复选框即可。

注意,这只适用于兼容的浏览器。我相信这与一些浏览器不允许你在输入元素上设置:after和:before有关。不幸的是,目前只支持WebKit浏览器。Firefox + Internet Explorer仍然允许复选框发挥作用,只是没有样式,这在未来有望改变(代码不使用供应商前缀)。

这是一个WebKit浏览器解决方案(Chrome, Safari,移动浏览器)

参见小提琴

$(function() { $('input').change(function() { $('div').html(Math.random()); }); }); /* Main Classes */ .myinput[type="checkbox"]:before { position: relative; display: block; width: 11px; height: 11px; border: 1px solid #808080; content: ""; background: #FFF; } .myinput[type="checkbox"]:after { position: relative; display: block; left: 2px; top: -11px; width: 7px; height: 7px; border-width: 1px; border-style: solid; border-color: #B3B3B3 #dcddde #dcddde #B3B3B3; content: ""; background-image: linear-gradient(135deg, #B1B6BE 0%, #FFF 100%); background-repeat: no-repeat; background-position: center; } .myinput[type="checkbox"]:checked:after { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%); } .myinput[type="checkbox"]:disabled:after { -webkit-filter: opacity(0.4); } .myinput[type="checkbox"]:not(:disabled):checked:hover:after { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%); } .myinput[type="checkbox"]:not(:disabled):hover:after { background-image: linear-gradient(135deg, #8BB0C2 0%, #FFF 100%); border-color: #85A9BB #92C2DA #92C2DA #85A9BB; } .myinput[type="checkbox"]:not(:disabled):hover:before { border-color: #3D7591; } /* Large checkboxes */ .myinput.large { height: 22px; width: 22px; } .myinput.large[type="checkbox"]:before { width: 20px; height: 20px; } .myinput.large[type="checkbox"]:after { top: -20px; width: 16px; height: 16px; } /* Custom checkbox */ .myinput.large.custom[type="checkbox"]:checked:after { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%, #FFF 100%); } .myinput.large.custom[type="checkbox"]:not(:disabled):checked:hover:after { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%, #FFF 100%); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table style="width:100%"> <tr> <td>Normal:</td> <td><input type="checkbox" /></td> <td><input type="checkbox" checked="checked" /></td> <td><input type="checkbox" disabled="disabled" /></td> <td><input type="checkbox" disabled="disabled" checked="checked" /></td> </tr> <tr> <td>Small:</td> <td><input type="checkbox" class="myinput" /></td> <td><input type="checkbox" checked="checked" class="myinput" /></td> <td><input type="checkbox" disabled="disabled" class="myinput" /></td> <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput" /></td> </tr> <tr> <td>Large:</td> <td><input type="checkbox" class="myinput large" /></td> <td><input type="checkbox" checked="checked" class="myinput large" /></td> <td><input type="checkbox" disabled="disabled" class="myinput large" /></td> <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large" /></td> </tr> <tr> <td>Custom icon:</td> <td><input type="checkbox" class="myinput large custom" /></td> <td><input type="checkbox" checked="checked" class="myinput large custom" /></td> <td><input type="checkbox" disabled="disabled" class="myinput large custom" /></td> <td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large custom" /></td> </tr> </table>

奖金Webkit风格的翻转开关小提琴

$(function() { var f = function() { $(this).next().text($(this).is(':checked') ? ':checked' : ':not(:checked)'); }; $('input').change(f).trigger('change'); }); body { font-family: arial; } .flipswitch { position: relative; background: white; width: 120px; height: 40px; -webkit-appearance: initial; border-radius: 3px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); outline: none; font-size: 14px; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; cursor: pointer; border: 1px solid #ddd; } .flipswitch:after { position: absolute; top: 5%; display: block; line-height: 32px; width: 45%; height: 90%; background: #fff; box-sizing: border-box; text-align: center; transition: all 0.3s ease-in 0s; color: black; border: #888 1px solid; border-radius: 3px; } .flipswitch:after { left: 2%; content: "OFF"; } .flipswitch:checked:after { left: 53%; content: "ON"; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <h2>Webkit friendly mobile-style checkbox/flipswitch</h2> <input type="checkbox" class="flipswitch" /> &nbsp; <span></span> <br> <input type="checkbox" checked="checked" class="flipswitch" /> &nbsp; <span></span>

从我的谷歌,这是最简单的方法复选框样式。只需根据您的设计添加:after和:checked:after CSS。

body{ background: #DDD; } span{ margin-left: 30px; } input[type=checkbox] { cursor: pointer; font-size: 17px; visibility: hidden; position: absolute; top: 0; left: 0; transform: scale(1.5); } input[type=checkbox]:after { content: " "; background-color: #fff; display: inline-block; color: #00BFF0; width: 14px; height: 19px; visibility: visible; border: 1px solid #FFF; padding: 0 3px; margin: 2px 0; border-radius: 8px; box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16); } input[type=checkbox]:checked:after { content: "\2714"; display: unset; font-weight: bold; } <input type="checkbox"> <span>Select Text</span>

看起来你只需要使用CSS就可以改变复选框的灰度颜色。

下面将复选框从黑色转换为灰色(这是我想要的):

input[type="checkbox"] {
    opacity: .5;
}