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 +).

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.

Note: Ideally I'm looking for a pure CSS solution without the need for JS. Let me know if this isn't possible.

Here's my code pen.

有帮助吗?

解决方案

I wrote a similar solution the other day, here.

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.

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, +.

No need for JS - UPDATED EXAMPLE

Modified 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>

Updated CSS:

input[name='panel']:checked ~ label .rotate {
    transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
}

It's worth noting that I moved the transition properties to the .rotate element too.

其他提示

jQuery Solution:

http://jsfiddle.net/SinisterSystems/PUwh6/2/

Use an ID so jQuery can map out what you're doing easily without searching for classes all over the place.

HTML:

<label for="panel">
  Click Me
  <div id="rotate">+</div>
</label>

CSS:

#rotate {
 width: 12px;
 float: right;
 font-size: 18px;
 margin-top: -6px;
 text-align: center;
 transition: all 1s ease;
 -o-transition: all 1s ease;
 -moz-transition: all 1s ease;
 -webkit-transition: all 1s ease;
 }
#rotate.spin {
 transform: rotate(45deg);
 -o-transform: rotate(45deg);
 -ms-transform: rotate(45deg);
 -webkit-transform: rotate(45deg);
}

jQuery:

$('#panel').on('click',function() {
  $('#rotate').toggleClass('spin');
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top