问题
I've hit this one a couple of times in the past and never walked away with a good solution. If I have several HTML elements that are positioned according to natural document flow. For the sake of example, let's say it's a simple stack of div
s. I would like to use CSS3 transitions to smoothly move one of those elements to a fixed location of the page (say 0,0) and then back to it's normal position.
The problem is that changing the position
style attribute to absolute
or fixed
if it wasn't there before will cause the position to snap and ignore any transition instructions. As such I would imagine that any such transition would involve some sort of javascript component to figure out where the element currently is and how far off from the desired point it is and so on and then dynamically build the CSS style from that.
That feels like an awful lot to go through for what seems like a trivial-ish case, though. Is there a better way?
回答1:
Yes, it would be cool that we could be able to transition from position static to absolute, but realistically I don't think it's coming soon (if ever). I'd be happy with just being able to transition from height: px
to height: auto;
.
My guess is that there is some sort of tradeoff when the browser has to make a calculation to interpolate between two 'incompatible' values. So, if you set height: 20px
and then want to transition to height: auto
, then the browser would have to imagine what would happend if it had position auto and the calculations could get intensive. It's not implemented in jQuery either, so I guess it breaks some tests, or it's just plain hacky.
If you architect your css knowing that you will need position absolute to always refer to the window, then the javascript is drastically more simple: you just have to toggle between its offset and 0, 0.
$(".hover").on("mouseover", function(){
$(this).css({
top: $(this).offset().top * -1,
left: $(this).offset().left * -1
})
});
http://jsfiddle.net/crUFY/
A more robust solution would involve cloning the dom element and hiding the original, then animating the clone to the top of the window. This way you can apply position: relative to the parent elements.
来源:https://stackoverflow.com/questions/8919622/css3-transition-from-normal-flow-position-to-absolute