我遇到了CSS转换问题,在尝试其他操作之前,我想了解问题所在。
容器中有3个盒子,还有一个“下一步”按钮。目的是使下一个框顶部显示在顶部,并在按下“下一步”按钮时淡入。该框通过将其附加到容器而位于顶部,因此它被添加为最后一个元素,因此在顶部可见,并且应通过CSS过渡淡入。
问题在于,在添加框之后,css转换似乎无法正常工作。
如果在未附加的box元素上进行测试,则css过渡效果很好。
Fiddle here,代码如下:
HTML:
<div class="container">
<div class="box red"></div>
<div class="box blue"></div>
<div class="box green"></div>
</div>
<div id="next">Next</div>
JS:
var container = $(".container");
// Save the current list order
var list = container.children(".box");
// The current index
var current = 0;
// Put the first on top
container.append(list[0]);
function next() {
// Figure out what is the index of the next box
if (current + 1 < list.length) current++;
else current = 0;
// Save it in a variable
var target = $(list[current]);
// Put it on top
container.append(target);
// Hide it and then fade it in
target.css("opacity", 0).css("transition", "opacity 1000ms ease-out").css("opacity", 1);
// The fading in is not working
}
$("#next").click(next);
更新:
此问题的基本解决方案是在将不透明度设置为0之后并在设置过渡CSS之前在目标上调用offset():
target.css("opacity", 0);
target.offset();
target.css("transition", "opacity 1000ms ease-out").css("opacity", 1);
Updated version of the above fiddle here
最佳答案
“列表”变量是一个jQuery对象,但是您从中将其作为“目标”拉出的元素是而不是 jQuery对象-它们是DOM节点。因此,您对“.css()”的调用失败了(在错误控制台中为我报告了该错误)。
解决此问题之后,接下来的问题就是浏览器如何处理一系列CSS更新。我尚不清楚我确切地看到了什么(从Linux上的Firefox 18),但是我认为基本问题是因为更改之间没有进行布局重排,所以最终的结果是样式被“折叠”,因此没有零钱。
在this update to the fiddle中,我采用了另一种方法。我将转换规则放在“box”类中,然后添加了“prefade”类:
.prefade {
transition-duration: 0;
opacity: 0;
}
然后,而不是弄乱元素样式,而是在追加之前添加“prefade”,然后通过询问元素的偏移量来触发布局更新。然后,我可以删除“prefade”类,然后该框就会淡入。
target.addClass('prefade');
// Put it on top
container.append(target);
var p = target.offset();
target.removeClass('prefade');
我不知道这是否是做事的“正确”方法。编辑-要使其在Chrome中运行,需要使用
-webkit-
前缀重复“transition”属性。关于javascript - 附加元素后CSS过渡不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14654803/