Style checkboxes as Toggle Buttons

馋奶兔 提交于 2019-12-05 02:15:51

Check this out

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>

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

Note that the last selector may not work in older IE.

This can be done using checkboxes and labels, the adjacent sibling selector – and the CSS3 :selected pseudo class.

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>

CSS:

input { display:none; }
input:checked ~ label { color:red; }

http://jsfiddle.net/drTg2/

But be aware that this will easily fail in older browsers – because they don’t know ~ or :checked. And older IE have problems with checkboxes set to display:none – won’t transfer them when the form is submitted (although that can be overcome by other means of hiding, f.e. absolute positioning of the screen).

If you don’t insist on a pure HTML/CSS solution – there are many scripts / {js-framework-of-your-choice}-plugins out there, that help achieve the same effect.

Checkboxes, radio buttons and SELECT elements have very limited styling capabilities and they vary widely across browsers.

You're better off accomplishing these using styled links or buttons, then using JavaScript to set the actual on/off appearance and form values.

klewis

You can borrow ideas from this page! Try to bind your text and checkbox. And then then try to use jquery to "toggle" the label associated to the checkbox.

You can then use styles and images to make the labels look like containers for checkboxes. That is what I would do.

You may try to have pictures with javascript onclick event that would change img source attribute. Then, put hidden control with given id and in the same onclick event use document.getElementById('hiddencontrol').value = 1 - document.getElementById('hiddencontrol').value (with 0 or 1 as default).

However, I don't know how to make it without Javascript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!