问题
I know you can set different durations for different properties with CSS transitions. But is it possible to set different durations for the same property?
Example: I want a box to grow/shrink in width to length A quickly when hovered/mouse exits, but grow/shrink in width to length B slowly when a button is pressed, using a different class.
Here is an example:
http://jsfiddle.net/VDyPG/7/
At the moment, the box only grows quickly when hovered, it shrinks back slowly when the mouse exits. Of course this is expected, as the .box
class has the slow duration speed applied, but is there a way around this? I have worked out a hacky way of doing it with setTimeout
and an extra "fast" class, but it would be lovely if there was a more elegant way.
Note: I'm aware this can be done easily with jQuery. I'm really looking for it to work with CSS however, as the actual problem I'm facing outside of this isolated example is with 3D transforms. Kept it simple for the example. :)
CSS:
.box {
background: red;
width: 100px;
height: 100px;
margin: 10px;
-webkit-transition: width 2s;
}
.lengthA
{
width: 300px;
-webkit-transition-duration: 0.2s; /* Can this be used when class removed? */
}
.lengthB {
width: 500px;
}
jQuery:
$('.box').on('mouseenter', function() {
$(this).addClass('lengthA');
})
$('.box').on('mouseleave', function() {
$(this).removeClass('lengthA');
})
$('.makeBig').on('click', function() {
$('.box').toggleClass('lengthB');
})
HTML:
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button class="makeBig">Grow!</button>
回答1:
I believe you can by using a variant of this technique: http://css-tricks.com/different-transitions-for-hover-on-hover-off/ . I'm on my iPad right now, so won't those out an example, but the gist of it is that you set a different transition on the hover pseudo selector.
If you want to use jquery, then you can bind to the transitioned event to find out when the previous transition as finished, it's worth noting that the naming isn't consistent -
You'll want to use something like:
$("div").bind("webkitTransitionEnd oTransitionEnd msTransitionEnd transitionEnd transitionend", function(){
//code
});
As it seems that Firefox uses transitionend, rather than the correct transitionEnd.
回答2:
You mean like this?:
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button class="makeBig">Grow!</button>
<style type="text/css">
.box {
width: 100px;
height: 100px;
margin: 10px;
background: red;
-webkit-transition: width 250ms ease;
}
.box:hover {
width: 500px;
}
.box.slow {
width: 500px;
-webkit-transition-duration: 2s;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(".makeBig").on("click", function() {
$('.box').addClass("slow");
})
</script>
来源:https://stackoverflow.com/questions/10902426/css-transitions-different-durations-with-the-same-property