以下是我在Safari中遇到的一个最小化的错误样本。
期望行为:代码应该在另一张图片加载时显示占位符,然后淡入该图像并删除占位符。
placeholder -> fading in loaded image
实际表现: 在Chrome和Mozilla中按预期工作,但在Safari中失败,导致以下效果:
placeholder -> white screen -> loaded image
请问有人能帮我解决为什么在Safari中会出现这种情况吗?(尝试在Chrome或Mozilla与Safari中运行下面的示例以查看结果。)
const image = new Image();
image.onload = () => {
document.getElementById('placeholder').remove();
const el = document.createElement('img');
el.setAttribute('src', 'http://deelay.me/1000/https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516_1280.jpg');
el.setAttribute('width', '150');
el.setAttribute('height', '150');
el.style = `
animation-name: testAnimation;
animation-duration: 0.3s;
animation-iteration-count: 1;
animation-timing-function: ease-in;
background: red;
`;
document.body.appendChild(el);
}
image.src = 'http://deelay.me/1000/https://cdn.pixabay.com/photo/2014/06/03/19/38/board-361516_1280.jpg';
#placeholder {
background: #eee;
}
@-webkit-keyframes testAnimation {
0% {
opacity: 0.25;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
<img id="placeholder" src="data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width%3D'200' height%3D'300' viewBox%3D'0 0 200 300'%2F%3E" width="150" height="150">
(
还有一个奇怪的行为是,如果将animation-duration
增加到大约3-4秒,那么图像确实会淡入,但是白色屏幕仍然存在,也就是说:
placeholder -> white screen -> fading in loaded image
)
更新:
在尝试调整img的背景颜色后,似乎在Safari浏览器中,动画效果开始生效的时间比图片渲染到屏幕上早了约1秒。
- 因此,如果真实图片没有像占位符图片一样的背景颜色,则会出现白色闪烁,因此在为真实图片添加背景颜色后,该背景颜色会在图片开始显示之前约1秒钟变得可见
- 因此,淡入淡出效果也会在图片开始显示之前约1秒钟开始发生
而在Chrome和Mozilla浏览器中,动画似乎与图片完全同步。
运行更新的代码以自己查看
(它似乎只发生在<img>
中,我已经测试过其他一些元素(仍在image.onload内)并且它们按预期工作。)
onload
事件,这次是在图像元素上而不是在Image对象上。 - linasmnew