Wait for css transition [duplicate]

浪子不回头ぞ 提交于 2019-12-01 05:02:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!