我正在学习如何在 CSS 中使用
transition:
。 但由于某种原因,我的图像不断闪烁,而不是给我流畅的动画。 我正在使用最新版本的 Chrome 在 Windows 10 中进行开发。 这是我的代码,非常简单:
function toggleClass() {
var box = document.getElementById('box');
box.className = box.className.match(/active/) ? '' : 'active';
}
#box {
width:200px;
height:200px;
background-color:#999;
opacity:0;
transform:translate(0,30px);
transition:background-color 0.6s ease, opacity 0.6s ease, transform 0.6s ease;
}
#box.active {
opacity:1;
transform:translate(0,0);
}
img {
width:100%;
display:block;
filter: grayscale(100%) brightness(120%);
mix-blend-mode:multiply;
}
#box:hover {
background-color:red;
}
<button type="button" onClick="toggleClass()">Toggle Image</button>
<div id="box" class="">
<img src="https://i.sstatic.net/GwYD1.jpg" alt="">
</div>
我想做的是,当我按下
Toggle Image
按钮时,我想要灰度淡入。然后,当我将鼠标悬停在图像上时,我希望它变成红色,因为它使用 mix-blend-mode
和 #box
应具有红色背景颜色。
问题是,每次我将
active
添加到 #box.active
时,图像不会“逐渐淡入”。 相反,一个实心灰色框会向上滚动并淡入。一旦灰色框完成动画,图像就会“捕捉”到视图中,就好像动画持续时间为 0 秒一样。 我不希望图像“捕捉”到视图中...我希望图像像灰色框一样平滑淡入。
我希望灰色框和灰色图片都能顺利地一起动画。
我该如何实现这一点?
编辑
我注意到,如果我添加行
#box.active {background-color:transparent;}
,那么图像就会淡入。但是图像太亮了。 应用 #box-active {background-color:#999;}
与原始问题存在相同的问题。
编辑2
我注意到,如果我添加这些行,它几乎可以满足我的需要
#box { background-color:rgba(155,155,155,1); }
#box.active { background-color:rgba(155,155,155,0.9);}
出于某种不寻常的原因,在活动类之前使用
rgba
以及 alpha 1 和 alpha 0.9,似乎有一点帮助。 现在我看到浏览器“尝试”平滑地制作动画,但现在非常不稳定。
尝试在子元素
transform: translateZ(0)
上添加 img
。
function toggleClass() {
var box = document.getElementById('box');
box.className = box.className.match(/active/) ? '' : 'active';
}
#box {
width:200px;
height:200px;
background-color:#999;
opacity:0;
transform:translate(0,30px);
transition:background-color 0.6s ease, opacity 0.6s ease, transform 0.6s ease;
}
#box.active {
opacity:1;
transform:translate(0,0);
}
img {
width:100%;
display:block;
filter: grayscale(100%) brightness(120%);
mix-blend-mode:multiply;
transform: translateZ(0); // this rules forces a new layer
}
#box:hover {
background-color:red;
}
<button type="button" onClick="toggleClass()">Toggle Image</button>
<div id="box" class="">
<img src="https://doggyholder.netlify.app/300/400" alt="">
</div>
理论上你的代码是正确的,这已经是 chrome 中的一个 bug 已经有一段时间了。
translateZ(0)
解决方法迫使 chrome 绘制单独的图层供 GPU 玩。您可以在这里找到有关图层的更多信息。 另请注意,如果您想要视觉一致性,则可能需要使用一些额外的供应商前缀样式。