2014-11-14 46 views
0

我想做一个颜色淡入淡出,并在完成时运行一次函数。我可以使用bind来执行此操作,它在transitionend上运行回调。这是有效的,但是针对与元素相关的每个转换运行。限制/控制CSS过渡结束调用

CSS

多次转变:输出(2) called

box-shadow: 2px 2px 5px red !important; 
transition: all 2s ease-out ;  

单过渡:输出called

transition: background-color 2s ease-out !important; 
background: red !important; 

jQuery的:

$("#currentBlock").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(event){ 
       log("called"); 
       $(this).unbind(event); 
      }); 

我想申请到的box-shadow的转变,但它调用transitionend两次,而不是一次。如何限制回调被调用的时间,或者如果再次调用它,则取消它。

+0

[transitionend event fire twice twice](http://stackoverflow.com/questions/18689031/transitionend-event-fire-twice) – 2014-11-14 21:55:11

回答

1

您对生产​​商特定事件以及标准事件都具有约束力。有些浏览器支持其中的一种以上。每个支持的事件越来越受限,并在过渡结束时调用。您应该测试以查看绑定之前支持哪些事件并仅绑定到其中一个事件。

2

多发射transitionend事件可以有两方面的原因:

  • 作为克里斯托弗·怀特在他回答说:某些浏览器支持多个transitionend事件,因此所有被解雇,因为你将它们绑定所有。 --->让jQuery检查前缀或前缀的版本,并仅绑定jQuery返回的结果。
  • 对于每个转换属性,将触发一个transitionend事件。所以转换盒子阴影和背景会导致两个事件。 --->在事件对象内部查找导致事件的属性的名称。然后你可以决定if语句做什么。

$('body').css('transition'); // this initializes the check for vendor-prefixed transitions 
console.log($.cssProps.transition); // in jQuery.cssProps you find the result 
$("#currentBlock").bind($.cssProps.transition + 'end', function(evt) { 
    // jQuery wraps the original event in an own object so we retrieve it from there 
    var prop = evt.originalEvent.propertyName; // in the original you find the property 
    console.log(prop); 
    // now you can for a specific transitionend decide what shall happen 
    if (prop == 'box-shadow') { // note the properties are dashed here 
     console.log('boxShadow has finished.'); 
    } 
    // if you want to unbind the handler argument is the event-name, not the event-object 
    $(this).unbind($.cssProps.transition + 'end'); 
}); 

BTW:如果您有jQuery的较新版本的使用.on()/.off()代替.bind()/unbind()