单击按钮时显示元素

时间:2019-05-22 07:10:51

标签: html css

是否可以仅使用HTML + CSS来检测该按钮是否被单击并显示(或添加一些样式)多个元素?因此,单击按钮后,我希望某些元素可见(并且当用户单击其他元素时仍然可见)。这是我到目前为止尝试过的(目标-使用“ .box”类显示元素):

/* works */
#button:checked + span {
  text-transform: uppercase;
}

/* not works :( */
#button:checked + .box {
  display: block;
}

/* set up */

input, .box { display: none;}

.btn {
  display: inline-block;
  padding: 1em 2em;
  background: linear-gradient(90deg, #5F6DFF 0%, rgba(195, 113,255, 0.88) 100%);
  box-shadow: 0px 4px 10px rgba(255, 95, 109, 0.25);
  border-radius: 40px;
  color: #fff;
  cursor: pointer;
  transition: all 0.1s linear;
}
<label class="btn" for="button">
  <input id="button" type="radio" />
  <span>Click me!</span>
</label>

<div class="containerOne">
  <div class="box">Im first</div>
  <div class="foo">Hello</div>
</div>

<div class="containerTwo">
  <div class="box">Im second</div>
  <div class="bar">world</div>
  <div class="box">Im third</div>
</div>

2 个答案:

答案 0 :(得分:5)

这只有在您这样更改HTML结构时才可能。

/* works */
#button:checked + label span {
  text-transform: uppercase;
}

/* not works :( */
#button:checked + .box {
  display: block;
}

/* set up */

input, .box { display: none;}

.btn {
  display: inline-block;
  padding: 1em 2em;
  background: linear-gradient(90deg, #5F6DFF 0%, rgba(195, 113,255, 0.88) 100%);
  box-shadow: 0px 4px 10px rgba(255, 95, 109, 0.25);
  border-radius: 40px;
  color: #fff;
  cursor: pointer;
  transition: all 0.1s linear;
}

input:checked ~ .box {
  display: block;
}
<div class="containerOne">
<input id="button" type="radio" />
<label class="btn" for="button">
  <span>Click me!</span>
</label>
  <div class="box">Im first</div>
  <div class="foo">Hello</div>
  <div class="box">Im second</div>
  <div class="bar">world</div>
  <div class="box">Im third</div>
<div>

答案 1 :(得分:1)

尝试这个:

/* works */
#button:checked + .btn span {
  text-transform: uppercase;
}

/* now works :) */
#button:checked ~ .containerOne .box, 
#button:checked ~ .containerTwo .box {
    display: block;
}
/* set up */

input, .box { display: none;}

.btn {
  display: inline-block;
  padding: 1em 2em;
  background: linear-gradient(90deg, #5F6DFF 0%, rgba(195, 113,255, 0.88) 100%);
  box-shadow: 0px 4px 10px rgba(255, 95, 109, 0.25);
  border-radius: 40px;
  color: #fff;
  cursor: pointer;
  transition: all 0.1s linear;
}
<input id="button" type="radio" />
<label class="btn" for="button">
  <span>Click me!</span>  
</label> 

<div class="containerOne">
  <div class="box">Im first</div>
  <div class="foo">Hello</div>
</div>

<div class="containerTwo"> 
  <div class="box">Im second</div>
  <div class="bar">world</div>
  <div class="box">Im third</div>
</div>