限制/控制CSS transitionend调用

时间:2014-11-14 21:33:13

标签: jquery css css3

我想做一个颜色渐变,并在完成后运行一次。我可以使用bind执行此操作,transitionend(2) called上运行回调。这是有效的,但是对于与元素绑定的每个转换都会运行。

CSS

多次转换:输出 box-shadow: 2px 2px 5px red !important; transition: all 2s ease-out ;

called

单一过渡:输出 transition: background-color 2s ease-out !important; background: red !important;

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

jQuery的:

transitionend

我想将过渡应用于box-shadow,但它会调用{{1}}两次,而不是一次。如何限制回调被调用的时间,或者如果再次调用它则取消它。

2 个答案:

答案 0 :(得分:2)

多个已解雇的transitionend事件可能有两个原因:

  • 正如 Christopher White 在他的回答中所说:有些浏览器支持多个transitionend事件,因此所有事件都被触发,因为你将它们全部绑定。 --->让jQuery检查无前缀或前缀版本,并仅绑定结果jQuery返回。
  • 对于每个转换的属性,会触发一个transitionend-event。因此,过渡框阴影和背景会导致两个事件。 --->在event-object内部查找导致该事件的属性的名称。然后你可以决定用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()

答案 1 :(得分:1)

您绑定制造商特定事件以及标准事件。有些浏览器支持多种浏览器。转换结束时,每个受支持的事件都会被绑定并调用。您应该测试以查看绑定之前支持哪些事件,然后绑定到其中一个事件。