问题
I am using css transitions to set the margin of one of my div. I need to know how can I wait for this effect to end so I can call other function then... Is there any way? I read some other posts on stack overflow but they all look different from my problem.
回答1:
Try This SO answer
The transition listner events vary in each browser, so the below function will find which listener to use and return the correct one.
function whichTransitionEvent(){
var t;
var el = document.createElement('fakeelement');
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
}
for(t in transitions){
if( el.style[t] !== undefined ){
return transitions[t];
}
}
}
var transitionEnd = whichTransitionEvent();
element.addEventListener(transitionEnd, theFunctionToInvoke, false);
function theFunctionToInvoke(){
// set margin of div here
}
回答2:
You could do it two ways (assuming the transition takes 1 second in each example):
1.) Animate that element with jQuery.animate (instead of CSS transition):
$('#mydiv').animate({
'margin-left': '10px',
}, {
duration: 1000,
complete: function () {
// do stuff after animation has finished here
}
});
2.) Animate after a set period of time:
window.setTimeout(function () {
// do stuff after animation has finished here
}, 1000);
EDIT: I understand that #2 is a bad solution, but I will keep this up in case other people were thinking down the same path I was.
来源:https://stackoverflow.com/questions/15617970/wait-for-css-transition