创建一个像html复选框一样的div

时间:2011-04-02 12:42:21

标签: javascript css html

我想在点击时打开/关闭div(它应该像html复选框一样)并使用css进行可见的更改。这可能没有Javascript,还是我必须使用Javascript?

如果您已创建此类脚本,请分享。

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:14)

只需使用CSS代码就可以轻松完成此操作,方法是隐藏复选框并为其标签设置样式,如下所示:

HTML

<div id="checkboxes">
    <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
    <label class="whatever" for="r1"></label>
    <input type="checkbox" name="rGroup" value="2" id="r2" />
    <label class="whatever" for="r2"></label>
    <input type="checkbox" name="rGroup" value="3" id="r3" />
    <label class="whatever" for="r3"></label>
</div>

CSS

.whatever{
    background-color: red;
    display: inline-block;
    width: 100px;
    height: 100px;
}

#checkboxes input[type=checkbox]{
    display: none;
}

#checkboxes input[type=checkbox]:checked + .whatever{
    background-color: green;
}

您可以在这里查看这个简单的代码:
JSFiddle

希望这可以帮助! :)

答案 1 :(得分:3)

你可以在没有javascript的情况下使用label元素来包装你想要点击的div:

<input name="checkbox1" id="checkbox1" type="checkbox">
<label for="checkbox1">
   Click me
</label>

和css:

input {
  display:none;
}
:checked + label {
  border: 1px solid rgba(81, 203, 238, 1);
  box-shadow: 0 0 5px rgba(81, 203, 238, 1);
}

请点击此处查看css样式http://jsfiddle.net/vyP7c/761/

的示例

答案 2 :(得分:2)

我一直试图回答你的问题,我创建了一个小jQuery(1.5.2)代码。 希望这有助于看看并告诉我这是你在寻找什么?或者如果你想要别的东西我也可以做到。在此脚本中单击标识为div的{​​{1}}元素(您也可以使用var来选择它)和on(on_off)和off(on_off_on)的类顺便你也可以选择它们,只需到这个jsFiddle链接 live demo或者您可以看到下面的脚本 -

HTML -

on_off_off

CSS -

<html>
     <head>
            <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js" ></script>
     </head>
     <body>
           <div id="on_off" class="on_off_on" >ON</div>
     </body>
</html>

jQuery代码 -

div.on_off_off
{
 background: rgb(150,110,120);
 font-family: segoe ui;
 font-size: 12px;
 font-weight: bold;
 padding: 5px 10px;
 border: 3px solid rgb(180, 140, 150);
 border-radius: 5px;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px;
 -khtml-border-radius: 5px;
 color: #fff;
 display: inline;
}
div.on_off_on
{
 background: rgb(110,150,120);
 font-family: segoe ui;
 font-size: 12px;
 font-weight: bold;
 padding: 5px 10px;
 border: 3px solid rgb(140, 180, 150);
 border-radius: 5px;
 -moz-border-radius: 5px;
 -webkit-border-radius: 5px;
 -khtml-border-radius: 5px;
 color: #fff;
 display: inline;
}

希望这会有所帮助!

答案 3 :(得分:0)

嗯,你必须使用javascript,这很简单。你只需要在行动中改变div的css样式。

<a href='javascript: toggle()'>toggle</a>
<div id='div1' style='display:none'>
Don't display me
</div>

<script>
function toggle(){
    var div1 = document.getElementById('div1')
    if (div1.style.display == 'none') {
        div1.style.display = 'block'
    } else {
        div1.style.display = 'none'
    }
}
</script>