jquery - 限制/控制 CSS transitionend 调用

标签 jquery css

我想做一个颜色淡入淡出,并在完成后运行一次函数。我可以使用 bind 执行此操作,它在 transitionend 上运行回调。这行得通,但会针对绑定(bind)到元素的每个转换运行。

CSS

多个转换:输出:(2) called

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

单一转换:输出:调用

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

jQuery:

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

我想对框阴影应用过渡,但它调用了两次 transitionend,而不是一次。如何限制回调被调用的时间量,或者如果再次调用则取消它。

最佳答案

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

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

关于jquery - 限制/控制 CSS transitionend 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939213/

相关文章:

jquery - 为什么我无法更改要提交的输入元素的类型?

javascript - jQuery - 仅在面板可见时切换关闭点击外部元素的面板

html - 媒体打印多页表格边框布局

javascript - jQuery Mobile,透明黑色叠加效果

css - 完全充满 map 的可变大小的 map 容器(最好在传单中)

php - 如何使用 JQuery 的 "load"函数来获取变量中所需的数据?

javascript - 用于减少要编写的 javascript 行数的技术

php - jquery 中的 Stack Overflow 样式标记系统

Html css 卡片对齐

html - 如何在html中为行制作斜线