我正在用 JavaScript 和 jQuery 编写一些应用程序,当使用事件时,有时我需要为多个浏览器指定相同的事件,例如 transitionend
、webkitTransitionEnd
、 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/