如何仅使用CSS在Div中切换效果?

问题描述:

注意:我尝试了所有问题&与该主题相关的答案.另外,我尝试了相关问题并尝试解决,但未成功.因此,请仔细阅读我的问题.

Note: I tried all questions & answers related this topic. Additionally and I tried related questions and try to solve it but not success. So please read my question deathly.

我想

  1. I click me Div,然后显示第二个hiddendiv Div.但是我想第二次单击click me Div,然后隐藏hiddendiv Div.使用纯CSS的类似切换事件.

  1. I click me Div then Second hiddendiv Div display. But I want to click a second time in click me Div, then hide a hiddendiv Div . Similar toggle event using pure css.

I click me Div,然后显示第二个hiddendiv Div.但是我单击其他区域,然后单击隐藏hiddendiv Div.因此,我不想在使用纯css的任何其他单击中隐藏hiddendiv Div.

I click me Div then Second hiddendiv Div display. But I click other area click then hide ahiddendiv Div . So I want to not hide ahiddendiv Div in any other click using pure css.

注意: 仅纯CSS,CSS3在答案"中使用,不使用( javascript,jquery )&其他任何控制因素

Note: Only pure CSS,CSS3 Use in Answer not use (javascript,jquery) & any other from control

代码

.clicker {
  width: 100px;
  height: 100px;
  background-color: blue;
  outline: none;
  cursor: pointer;
  color:#FFF;
}

.hiddendiv {
  display: none;
  height: 200px;
  background-color: green;
}

.clicker:focus+.hiddendiv {
  display: block;
}

<div>
  <div class="clicker" tabindex="1">Click me</div>
  <div class="hiddendiv"></div>
</div>

对于给定的要求,这是不可能的,因为所有元素都是div.

That is not possible with the given requirements, all elements being a div.

如果更改div作为锚点a的链接,并使用:target

It would be possible if you change div's acting as links to anchors a, and use :target pseudo

通过在锚点a上设置display: inline-block,您可以使用div

By setting display: inline-block on the anchor a, you can size it as you can with a div

.clicker {
  display: inline-block;
  width: 100px;
  height: 50px;
  background-color: blue;
  color:#FFF;
}
.clicker.hidden {
  display: none;
}
.hiddendiv {
  height: 0px;
  background-color: green;
  overflow: hidden;
  transition: height 0.5s;
}
.hiddendiv.nr2 {
  background-color: red;
}

#showdiv1:target ~ div a[href="#showdiv1"],
#showdiv2:target ~ div a[href="#showdiv2"] {
  display: none;
}
#showdiv1:target ~ div a[href="#hidediv1"],
#showdiv2:target ~ div a[href="#hidediv2"] {
  display: inline-block;
}
#showdiv1:target ~ div .hiddendiv.nr1,
#showdiv2:target ~ div .hiddendiv.nr2 {
  height: 150px;
}

<div id="showdiv1"></div>
<div id="showdiv2"></div>

<div>
  <a href="#showdiv1" class="clicker" tabindex="1">Click me 1</a>
  <a href="#hidediv1" class="clicker hidden" tabindex="1">Click me 1</a>

  <a href="#showdiv2" class="clicker" tabindex="2">Click me 2</a>
  <a href="#hidediv2" class="clicker hidden" tabindex="2">Click me 2</a>

  <div class="hiddendiv nr1"></div>
  <div class="hiddendiv nr2"></div>
</div>