Javascript “显示动画”不是动画
我正在开发一个使用AJAX调用隐藏、显示和替换元素的函数。一切都很完美,它为关闭设置了动画,但由于某些原因,当它打开时不会重新激活,它只是出现。这是一个相当长的脚本,所以这是很重要的内容:Javascript “显示动画”不是动画,javascript,jquery,animation,Javascript,Jquery,Animation,我正在开发一个使用AJAX调用隐藏、显示和替换元素的函数。一切都很完美,它为关闭设置了动画,但由于某些原因,当它打开时不会重新激活,它只是出现。这是一个相当长的脚本,所以这是很重要的内容: // This is the first part which is executed. var bar = $("#bar"); // This is what happens when the bar is closes and works. if (!supressed) { ba
// This is the first part which is executed.
var bar = $("#bar");
// This is what happens when the bar is closes and works.
if (!supressed) {
bar.animate({height:0});
bar.parent().animate({height:0}, function() {
$(this).hide()
});
} else {
// The bar is replaced with an identical div with the same id.
bar.replaceWith(newBar);
if (supressed) {
// When the bar needs to appear again it runs the updateBar function.
updateBar(true);
}
}
这是updateBar函数。#bar div刚刚出现,但不会在视图中设置动画。我尝试过切换动画调用的顺序,但两种方法都没有奏效
function updateBar(reload) {
// Reassigns the variable
var bar = $("#bar");
if (reload === true) {
// This is where things go wrong.
bar.animate({height:"45px"});
bar.parent().animate({height:"45px"}, function() {
$(this).show();
});
}
}
JSFiddle:
有什么建议吗?我可以通过在设置显示之前隐藏条的父项来解决这个问题。像这样:
bar.animate({height:"45px"});
bar.parent().animate({height:"45px"}, function() {
$(this).hide.show("slow");
});
您的原始脚本的问题在于,您正在为父对象的高度设置动画,而父对象是隐藏的。然后在动画完成后显示它。因此,高度动画不可见。您可以通过插入
console.log($(this.css('display'))来判断这一点代码>显示父级之前。控制台将显示none
我不知道你为什么还要给父对象设置动画。如果只想隐藏/显示该栏,可以执行以下操作:
function reloadBar() {
var $bar = $("#bar");
var $newBar = $("#new-bar");
$bar.replaceWith($newBar);
if ($("#click").hasClass("clicked")) {
$newBar.animate({ height: 0 })
} else {
$newBar.animate({ height: '45px' });
}
}
或者,您可以更改reload()
函数,在设置高度动画之前先显示父对象,如下所示:
function reload(option) {
var $bar = $("#new-bar");
if (option === true) {
$bar.animate({
height: "45px"
});
$bar.parent().show().animate({
height: "45px"
});
}
}
function reload(option) {
var $bar = $("#new-bar");
if (option === true) {
$bar.css({ height: "45px" });
$bar.parent().show().animate({
height: "45px"
});
}
}
但是上面的冗余在于,$bar
的动画没有意义,因为$bar不可见(即,$bar
的父项具有显示:无)。所以你可以像这样完全移除它:
function reload(option) {
var $bar = $("#new-bar");
if (option === true) {
$bar.animate({
height: "45px"
});
$bar.parent().show().animate({
height: "45px"
});
}
}
function reload(option) {
var $bar = $("#new-bar");
if (option === true) {
$bar.css({ height: "45px" });
$bar.parent().show().animate({
height: "45px"
});
}
}
或者,您可以简单地设置条形图高度的动画,让父对象保持原样,就像我之前所做的那样。调用条形图父对象上的$(this).hide()
将其显示属性设置为无。因此,当您调用updateBar()
以将条形图及其父对象重新设置为动画时,父对象将保持隐藏状态,直到动画完成并调用$(this).show()
因此,在updateBar()
中,只需在开始动画之前调用bar.parent().show()
更新的小提琴:你说的“打开备份”是什么意思?关闭时是否重置值?@tq的想法是,它将在关闭的同一个庄园中设置打开动画。所有隐藏/显示都发生在示例中。可能是我在动画关闭后替换html元素,所以它不再具有相同的高度属性?为什么不提供一个?确定的东西@OscarJara-你会看到在最初的替换之后,动画不再正常工作:-我几乎可以肯定,一旦我替换DOM元素,它与CSS被核化有关,我只是不确定在它被替换后,将其重置回隐藏状态的最佳方法。