【发布时间】:2020-04-06 11:11:45
【问题描述】:
我最喜欢的最终目标是拥有一个性能友好的背景,可以流畅地循环而不会跳跃。我在网上找到的所有资源要么对性能不太友好,要么只适用于具有固定宽度的元素。
目前一切看起来都还不错,但背景在不同屏幕上的缩放比例很差,并且偶尔会出现较大的跳跃。我认为跳跃是由于元素翻译中的错误,但我还没有看到一个好的解决方案。将元素的宽度设置为 200% 并将它们转换为 -50% 以上似乎是一个 hacky 解决方案,我觉得应该有更好的方法。
我更希望找到一个全 CSS 的解决方案,但如果没有其他可行的方法,诉诸 JS 就可以了。
小提琴:https://jsfiddle.net/r4fz0Lot/3/
代码:
* { box-sizing: border-box; }
html, body, #container { width: 100%; height: 100%; }
body { margin: 0; }
#container {
background-color: rgba(0, 0, 0, 0.9);
image-rendering: pixelated;
overflow: hidden;
position: fixed;
}
#stars {
background: url('https://i.imgur.com/Ym03Zkf.png') repeat 0 0;
animation: loop 25s linear infinite;
z-index: 1;
}
#mountains {
background: url('https://i.imgur.com/jfef1r3.png') repeat-x 0 bottom;
animation: loop 20s linear infinite;
z-index: 2;
}
#ground {
background: url('https://i.imgur.com/P13CzUo.png') repeat-x 0 bottom;
animation: loop 15s linear infinite;
z-index: 3;
}
#stars, #mountains, #ground {
width: 200%; height: 100%;
background-size: 30%;
bottom: 0; left: 0;
position: fixed;
}
@keyframes loop {
from { transform: translateX(0); }
to { transform: translateX(-50%); }
}
<div id="container">
<div id="ground"></div>
<div id="mountains"></div>
<div id="stars"></div>
</div>
【问题讨论】:
-
很酷的样子。顺便说一句,在 Firefox 上你有这个问题,可能只在 JS Fiddle 上:stackoverflow.com/q/54486441/7586
标签: javascript html css loops parallax