匿名用户
您正在设置页面负载的不透明度,因此它从技术上永远不会改变,并且没有任何需要转换的内容。 您需要在下一个事件循环中应用更改,您可以使用SetTimeout(。。。,0)(或使用RequestAnimationFrame):
nulllet green = document.createElement('div'),
red = document.createElement('div');
green.style = 'width: 200px; height: 200px; background-color: green; opacity: 0; transition: opacity 1s linear;',
red.style = 'width: 200px; height: 200px; background-color: red; opacity: 0; transition: opacity 1s linear;';
document.body.appendChild(green),
document.body.appendChild(red);
// the box's opacity is set to 0 when this script runs,
// but when the callback below is executed, it will be
// set to 1, triggering the actual transition
setTimeout(() => red.style.opacity = 1, 0);
// requestAnimationFrame will do effectively the same
// thing, but will try to wait until a frame is rendered.
// setTimeout(..., 0) will execute on the next event loop
// regardless of frame rate
requestAnimationFrame(() => green.style.opacity = 1, 0);body {
display: flex;
flex-direction: row;
}