javascript - jQuery 更好的事件

标签 javascript jquery jquery-events

我正在用 JavaScript 和 jQuery 编写一些应用程序,当使用事件时,有时我需要为多个浏览器指定相同的事件,例如 transitionendwebkitTransitionEnd MSTransitionEnd.

如果我在 100 个地方使用这个事件,当浏览器删除前缀时,我将很难删除其中的一些。我想知道是否有某种方法可以只将“transitionend”放在那里并在代码的其他部分添加其他部分,但只能添加一次。

最佳答案

您可以将所有事件放在代码中的一个字符串中,这样只有一个地方可以管理它。而且,如果您同时使用 .on().off(),您也可以使用命名空间:

// declare in a single place available to all your code
// In the future, you can remove any one of these and it will be used
// by all your code
var transitionEvents = "transitionend webkitTransitionEnd MSTransitionEnd";

然后,你可以像这样使用它:

$("#myObj").on(transitionEvents, function() {
    // code here
});

如果您还想在事件处理程序触发后删除它们,您可以使用命名空间来帮助实现:

// define all transition events with a namespace
var transitionEvents = "transitionend.tend webkitTransitionEnd.tend MSTransitionEnd.tend";

然后,你可以像这样使用它:

$("#myObj").on(transitionEvents, function() {
    // remove all transition event handlers using the namespace
    $(this).off(".tend");

    // put code here for the end of the transition
});

您也可以创建自己的 jQuery 插件方法来为您处理此问题:

// method to handle transition end and remove all handlers when the event fires
jQuery.fn.onTransitionEnd = function(fn) {
    var transitionEvents = "transitionend.tend webkitTransitionEnd.tend MSTransitionEnd.tend";
    this.on(transitionEvents, function(e) {
        $(this).off(".tend");
        return fn.call(this, e);
    });
}

然后你会像这样使用它:

$("#myObj").onTransitionEnd(function(e) {
    // code here for the end of the transition
});

关于javascript - jQuery 更好的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090182/

相关文章:

javascript - Dojo 1.6 hitch() "this"范围在 require 语句中

php - 从php中的文件目录中删除文件扩展名

javascript - 如果 li 为空,则在 jQuery 中隐藏 excluding span 属性

javascript - 如何为按钮设置图像和为图像设置悬停效果

javascript - jQuery .submit 方法

javascript - 有没有办法在基于 webkit 的浏览器中强制使用 Javascript 垃圾收集器?

javascript - 间歇性 JavaScript 问题

jquery - 使用 $.each 循环 jquery 来自 json 对象的相同键的总和

javascript - 按需滚动加载数据

javascript - 在 JavaScript 中从数组异步调用函数