【问题标题】:Why can't my checkbox affect my div contents?为什么我的复选框不能影响我的 div 内容?
【发布时间】:2022-01-07 11:56:16
【问题描述】:

我有一个复选框和一个 div 元素。 当我单击复选框时, div 元素的内容应该旋转以形成十字形。但它不这样做。 下面是代码

:root {
  --main-color: red;
  --secondary-color: blue;
  --dark-color: #444;
  --light-color: #fafafa;
}

body {
  font-family: 'Montserrat', sans-serif;
  text-align: justify;
  margin: 0px;
  display: grid;
  place-items: center;
  font-size: 18px;
}

input {
  box-sizing: border-box;
}

.toggle {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

span {
  height: 20px;
  width: 100px;
  display: grid;
  place-items: center;
  background-color: blue;
  margin: 5px 0;
}

.check:checked~span {
  background: red;
}

.check:checked~.span-one {
  position: relative;
  top: 100%;
  transform: rotate(45deg);
  transition: 400ms;
}

.check:checked~.span-two {
  position: relative;
  opacity: 0;
  transition: 400ms;
}

.check:checked~.span-three {
  position: relative;
  bottom: 100%;
  transform: rotate(-45deg);
  transition: 400ms;
}
<input class="check" type="checkbox">
<div>
  <span class="span-one"></span>
  <span class="span-two"></span>
  <span class="span-three"></span>
</div>

它可以在没有 div 的情况下工作,但我需要 div 来做其他事情,所以我无法删除它。

我该如何解决这个问题?

【问题讨论】:

  • 如果您添加 div,它们会移动,但不会交叉:.check:checked~div&gt;span

标签: html css checkbox css-transforms


【解决方案1】:

:root {
  --main-color: red;
  --secondary-color: blue;
  --dark-color: #444;
  --light-color: #fafafa;
}

body {
  font-family: 'Montserrat', sans-serif;
  text-align: justify;
  margin: 0px;
  display: grid;
  place-items: center;
  font-size: 18px;
}

input {
  box-sizing: border-box;
}

.toggle {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

span {
  height: 20px;
  width: 100px;
  display: grid;
  place-items: center;
  background-color: blue;
  margin: 5px 0;
}

.check:checked ~ div span { /* We need to make the div the sibling instead of the span */
  background: red;
}

.check:checked ~ div .span-one {
  position: relative;
  top: 50px; /* Changed from 100% */
  transform: rotate(45deg);
  transition: 400ms;
}

.check:checked ~ div .span-two {
  position: relative;
  opacity: 0;
  transition: 400ms;
}

.check:checked ~ div .span-three {
  position: relative;
  bottom: 100%;
  transform: rotate(-45deg);
  transition: 400ms;
}
<input class="check" type="checkbox">
<div>
  <span class="span-one"></span>
  <span class="span-two"></span>
  <span class="span-three"></span>
</div>

【讨论】:

  • OP 知道:It works without the div but I need the div for something else so I can't remove that.
  • 我的错,已修复:D
  • 终于有工作版了
猜你喜欢
  • 2011-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 2015-08-21
相关资源
最近更新 更多