问题描述:

I'm experimenting with the checkbox hack to show and hide a list of external links, without using for= and JavaScript.

HTML:

<label class="tog">

<input type="checkbox" class="tog-check">

<div class="tog-list">

<a href="http://www.google.com">Google</a>

<a href="http://www.yahoo.com">Yahoo</a>

<div class="tog-less">

hide

</div>

</div>

<div class="tog-more">

show

</div>

</label>

CSS:

label.tog{

display:block;

cursor:pointer;

}

input.tog-check{

position: absolute;

top: -9999px;

left: -9999px;

}

div.tog-list{

display:none;

}

input.tog-check:checked ~ div.tog-list {

display:block;

}

input.tog-check:checked ~ div.tog-more {

display:none;

}

input.tog-check:unchecked ~ div.tog-more {

display:block;

}

input.tog-check:unchecked ~ div.tog-list {

display:none;

}

div.tog-list a{

display:block;

padding:8px 4px;

border-bottom:1px solid #eee;

}

.tog-more, .tog-less{

padding:8px 4px;

border-bottom:1px solid #eee;

}

You can see it works. But this is invalid HTML as flow content is not allowed inside labels.

Is it possible to have .tog-list outside the label but still have show/hide functionality? Or am I stuck to using for=? Or is there some way around this?

网友答案:

I know this is a very old question but I just happened upon it and it piqued my interest.

You don't have to have it all in a label, just position the input over the show/hide elements.

E.G

.tog{
  display:block;
  position:relative;
  color:#ccc;
  cursor:pointer;
  font-weight:normal;
  margin:0;
}
.tog * {
  box-sizing:border-box;
}
.tog-check {
  position:absolute;
  bottom:0px;
  right:0px;
  left:0px;
  width:100%;
  height:2.5em;
  opacity:0.00015;
  outline:1px solid red;
  box-sizing:border-box;
}
.tog div {
  overflow:hidden;
  max-height:100px;
}
.tog-list {
  transition:0.5s;
}
.tog .tog-list,
.tog .tog-less,
.tog .tog-check:checked ~ .tog-more {
  max-height:0px;
}
.tog .tog-check:checked ~ .tog-list,
.tog .tog-check:checked ~ .tog-less {
  max-height:100px;
}
.tog-list a,
.tog-more,
.tog-less {
  display:block;
  padding:0px 4px;
  line-height:2em;
}
.tog-list a{
  border-bottom:1px solid #eee;
}
<div class="tog">
  <input type="checkbox" class="tog-check" />
  <div class="tog-list">
    <a href="http://www.google.com" target="_blank">Google</a>
    <a href="http://www.yahoo.com">Yahoo</a>
  </div>
  <div class="tog-less">[-] less</div>
  <div class="tog-more">[+] more</div>
</div>
相关阅读:
Top