附加元素后CSS过渡不起作用

jsg*_*ove 5 javascript css jquery

我遇到了CSS转换问题,在尝试其他操作之前,我想了解问题所在。

容器中有3个盒子,还有一个“下一步”按钮。目的是使下一个框顶部显示在顶部,并在按下“下一步”按钮时淡入。该框通过将其附加到容器而位于顶部,因此它被添加为最后一个元素,因此在顶部可见,并且应通过CSS过渡淡入。

问题在于,在添加框之后,css转换似乎无法正常工作。如果在未附加的box元素上进行测试,则css过渡效果很好。

在这里摆弄,下面的代码:

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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

更新

此问题的基本解决方案是在将不透明度设置为0之后并在设置过渡CSS之前在目标上调用offset():

target.css("opacity", 0);
target.offset();
target.css("transition", "opacity 1000ms ease-out").css("opacity", 1);
Run Code Online (Sandbox Code Playgroud)

上面的小提琴的更新版本在这里

Poi*_*nty 2

“list”变量是一个 jQuery 对象,但作为“目标”从中提取的元素不是jQuery对象 - 它们是 DOM 节点。因此,您对“.css()”的调用失败(在错误控制台中为我报告)。

一旦解决了这个问题,接下来的问题就是浏览器如何处理一系列 CSS 更新的问题。我不清楚我到底看到了什么(来自 Linux 上的 Firefox 18),但我认为基本问题是,因为更改之间没有进行布局重排,所以最终效果是样式“折叠”,因此没有净变化。

这次小提琴更新中,我采取了不同的方法。我将转换规则放在“box”类中,然后添加了一个“prefade”类:

.prefade {
  transition-duration: 0;
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)

然后,我不会弄乱元素样式,而是在附加之前添加“prefade”,然后通过询问元素的偏移量来触发布局更新。然后我可以删除“prefade”类,并且该框会淡入。

target.addClass('prefade');
// Put it on top
container.append(target);

var p = target.offset();

target.removeClass('prefade'); 
Run Code Online (Sandbox Code Playgroud)

我不知道这是否是“正确”的做事方式。编辑- 要使其在 Chrome 中工作,需要使用前缀重复“transition”属性-webkit-