使用 jQuery 切换带有动画的元素的简洁方法
Clean way of toggling elements with animation with jQuery
我需要切换元素并为它们制作动画。 toggle/animate 必须以不同的顺序排列,这使得这很棘手。
这是我现在拥有的:
var isActive = false;
$("a.handle").click(function() {
if (isActive == false) {
$("div.element").show();
$("div.element").toggleClass("fadeInRight fadeOutRight");
isActive = true;
}
else {
$("div.element").toggleClass("fadeInRight fadeOutRight");
$("div.element").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { $("div.element").hide(); } );
isActive = false;
}
});
它有效,但我觉得必须有更有效的写法。如果没有 isActive
变量,有没有办法做到这一点?
您可以删除 isActive
变量并使用 jquery hasClass()
方法。像这样:
$("a.handle").click(function() {
if ($("div.element").hasClass("fadeInRight")) { // or $("div.element").hasClass("fadeOutRight") based on your need...
$("div.element").show();
$("div.element").toggleClass("fadeInRight fadeOutRight");
}
else {
$("div.element").toggleClass("fadeInRight fadeOutRight");
$("div.element").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { $("div.element").hide(); } );
}
});
我相信您可以将一个选择器添加到您当前的选择器 $("a.handle")。只需在 $("a.handle:visible") 末尾添加 :visible 选择器即可。
编辑:实际上我必须添加这个是如果元素没有占用任何白色 space。
我需要切换元素并为它们制作动画。 toggle/animate 必须以不同的顺序排列,这使得这很棘手。
这是我现在拥有的:
var isActive = false;
$("a.handle").click(function() {
if (isActive == false) {
$("div.element").show();
$("div.element").toggleClass("fadeInRight fadeOutRight");
isActive = true;
}
else {
$("div.element").toggleClass("fadeInRight fadeOutRight");
$("div.element").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { $("div.element").hide(); } );
isActive = false;
}
});
它有效,但我觉得必须有更有效的写法。如果没有 isActive
变量,有没有办法做到这一点?
您可以删除 isActive
变量并使用 jquery hasClass()
方法。像这样:
$("a.handle").click(function() {
if ($("div.element").hasClass("fadeInRight")) { // or $("div.element").hasClass("fadeOutRight") based on your need...
$("div.element").show();
$("div.element").toggleClass("fadeInRight fadeOutRight");
}
else {
$("div.element").toggleClass("fadeInRight fadeOutRight");
$("div.element").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() { $("div.element").hide(); } );
}
});
我相信您可以将一个选择器添加到您当前的选择器 $("a.handle")。只需在 $("a.handle:visible") 末尾添加 :visible 选择器即可。
编辑:实际上我必须添加这个是如果元素没有占用任何白色 space。