样式复选框为切换按钮

Swe*_*wen 9 html css checkbox toggle

在我的网站上,用户可以使用一些预设标签发布文章并相应地标记它们.这些标签采用复选框的形式.示例如下:

<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Aliens" /> Aliens
<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Ghosts" /> Ghosts
<input type="checkbox" name="wpuf_post_tags[]" class="new-post-tags" value="Monsters" /> Monsters
Run Code Online (Sandbox Code Playgroud)

您可能知道,复选框看起来像这样:

[]外星人

[o]幽灵

[]怪物

我想要的是将复选框设置为一个大按钮,其中包含值.然后让它具有"切换"效果.

[外星人] [幽灵] [怪物]

我该怎么做呢?

Sim*_*mon 8

检查

HTML

<input id="chk_aliens" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Aliens" />
<label for="chk_aliens">Aliens</label>

<input id="chk_ghosts" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Ghosts" />
<label for="chk_ghosts">Ghosts</label>

<input id="chk_monsters" type="checkbox" name="wpuf_post_tags[]" class="vis-hidden new-post-tags" value="Monsters" />
<label for="chk_monsters">Monsters</label>
Run Code Online (Sandbox Code Playgroud)

CSS

.vis-hidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

label {
  margin: 10px;
  padding: 5px;
  border: 1px solid gray;
}

input:focus + label {
  border-color: blue;
}

input:checked + label {
  border-color: red;
}

input:focus:checked + label {
  border-color: green;
}
Run Code Online (Sandbox Code Playgroud)

请注意,最后一个选择器可能无法在较旧的IE中使用.

  • 我有一个类似的例子[这里](http://jsfiddle.net/cherryflavourpez/r7vXE/),基于[这篇CSS Ninja文章](http://www.thecssninja.com/css/custom-inputs-using- CSS).根据那篇文章,IE8及以下版本不支持`:checked`伪类,因此在这些浏览器中分崩离析.因此,您需要确保只为有能力的浏览器提供这些样式 - 一种方法是使用`not()`伪类 - 或者将它们全部放在媒体查询中. (3认同)

CBr*_*roe 7

这可以使用复选框和标签,相邻的兄弟选择器和CSS3 :selected伪类来完成.

HTML:

<span><input type="checkbox" id="c1"><label for="c1">[ Aliens ]</label></span>
<span><input type="checkbox" id="c2"><label for="c2">[ Ghosts ]</label></span>
<span><input type="checkbox" id="c3"><label for="c3">[ Monsters ]</label></span>
Run Code Online (Sandbox Code Playgroud)

CSS:

input { display:none; }
input:checked ~ label { color:red; }
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/drTg2/

但请注意,这在旧版浏览器中很容易失败 - 因为他们不知道~:checked.而旧的IE在设置复选框时遇到问题display:none- 在提交表单时不会传输它们(虽然可以通过其他隐藏方式克服屏幕的绝对定位).

如果你不坚持纯HTML/CSS解决方案 - 那里有许多脚本/ {js-frame-of-your-choice} -plugins,这有助于达到同样的效果.

  • 实际上,Simon使用选择器`input:checked + label`的答案更可取 - 我使用〜取决于输入和标签被封装在另一个元素(span)中. (2认同)