How do I use transitionend in jQuery?

前端 未结 5 839
说谎
说谎 2020-12-01 05:08

I need to detect if a CSS transition is completed before allowing a function to repeat again, to prevent messing up the margins.

So how cam I have something like

5条回答
  •  情书的邮戳
    2020-12-01 05:37

    You can create a method which will keep in mind when the transition end has been called the last time, and thus only trigger the callback once.

    function transitionEndsOnce($dom, callback) {
      var tick = Date.now();
      $dom.on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function(e) {
        var diff = Date.now() - tick;
        tick = Date.now();
        if (diff > 20) { // this number can be changed, but normally all the event trigger are done in the same time
          return callback && callback(e);
        }
      });
    }
    

    and then simply use it this way

    transitionEndsOnce($('...'), function(e){
      console.log('transition ends once');
    });
    

提交回复
热议问题