【问题标题】:Limit/Control CSS transitionend calls限制/控制 CSS 过渡结束调用
【发布时间】:2014-11-15 21:47:48
【问题描述】:

我想做一个颜色渐变,并在完成后运行一次函数。我可以使用bind 来做到这一点,它在transitionend 上运行回调。这可行,但会针对与元素关联的每个过渡运行。

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 两次,而不是一次。如何限制回调被调用的时间,或者如果再次调用则取消它。

【问题讨论】:

标签: jquery css


【解决方案1】:

多个触发的 transitionend-events 可能有两个原因:

  • 正如Christopher White 在他的回答中所说:有些浏览器支持多个transitionend 事件,因此所有事件都会被触发,因为您将它们全部绑定。 ---> 让 jQuery 检查无前缀或有前缀的版本,并只绑定 jQuery 返回的结果。
  • 对于每个已转换的属性,都会触发一个 transitionend-event。所以转换 box-shadow 和 background 会导致两个事件。 ---> 在事件对象中查找导致事件的属性的名称。然后,您可以使用 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');
});

顺便说一句:如果您有更新版本的 jQuery,请使用 .on() / .off() 而不是 .bind() / unbind()

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2013-05-19
      • 2022-12-25
      • 2015-10-12
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多