基于输入复选框状态应用CSS规则 [英] Applying CSS rules based on input checkbox status
问题描述
我目前正在开发一个网站,使用:checked变量来应用规则到CSS。我有一个复选框输入,触发时,应该完成两件事。它应该做的第一件事是扩展一个div从0到200的高度检查时,并返回到0,当未选中。我没有触发第一个任务的问题。 应该在检查盒子时完成的第二件事是:transform(45deg)of div with a + in which that should rotate 45 degrees into一个 x (不是实际的x,而是旋转的+)。
I'm currently developing a site that uses the :checked variable to apply rules to the CSS. I've got a checkbox input that when triggered, should accomplish two things. The first thing it should do is expand a div from a height of 0 to 200 when checked, and back to 0 when unchecked. I had no problems with triggering that first task. The second thing that should be accomplished upon checking the box, is a transform: rotate(45deg) of a div with a "+" in it that should rotate 45 degrees into an "x" (not an actual x, but a rotated +).
on:hover,但这只是为了说明的目的,这不会在我的最终代码。因此,将鼠标悬停在 + 上以查看我要使用:checked输入完成的操作。
I've currently got my code setup to display the animation on :hover, but that's just for illustrative purposes, that wouldn't be in my final code. So hover over the "+ to see what I'm trying to accomplish with the :checked input.
如果您愿意看看我的代码,告诉我我做错了,我会大大
If you're willing to take a look at my code, and tell me what I'm doing wrong, I'd be greatly appreciative! Let me know if you have any questions.
注意:理想情况下,我需要一个纯CSS解决方案,而不需要JS。让我知道
Here's my code pen.
推荐答案
有一天我写了一个类似的解决方案,此处。
I wrote a similar solution the other day, here.
基本上,您在使用:checked
方法时受到限制。您依赖于相邻和一般同胞组合器, +
, 〜
。
Basically, you are limited when using the :checked
method. You are relying on the adjacent and general sibling combinators, +
, ~
. If the element isn't a general preceding sibling, it isn't going to work.
在这个例子中, .expand $ c如果元素不是一个前面的兄弟, $ c>不是前一个兄弟。因此,解决方案是将
输入
元素放在文档的根处,然后使用选择器 input [name ='panel']:checked 〜label .rotate
更改 .rotate
元素。注意,现在也使用一般的同级组合器〜
,而不是相邻的同级组合器 +
。
In this example, .expand
was not a preceding sibling. Therefore the solution is to place the input
element at the root of the document, and then use the selector input[name='panel']:checked ~ label .rotate
to change the .rotate
element. Note, that the general sibling combinator, ~
is now also being used as opposed to the adjacent sibling combinator, +
.
不需要JS - 更新示例
No need for JS - UPDATED EXAMPLE
修改的HTML :
<input type="checkbox" name="panel" class="hidden" id="panel"/>
<label for="panel">
Click Me
<div class="rotate">+</div>
</label>
<div class="expand">
Content goes here.
</div>
更新的CSS :
input[name='panel']:checked ~ label .rotate {
transform: rotate(45deg);
-o-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
}
$ b $ p
值得注意的是,我将转换属性移动到 .rotate
元素。
这篇关于基于输入复选框状态应用CSS规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!