我做网页只是为了娱乐一下。当第一次加载页面时,我希望后台图像不断地向左滚动。图像被设置为在CSS中重复-x,并且在端到端放置时是无缝的.我写的这段代码是朝着正确的方向吗?
为了简单起见,我希望保留JS的风格,但是如果JQuery、CSS或其他库处理得更好,我会留心的。
我会非常感谢你的帮助!
我已经在一个简单的JavaScript文档中尝试了一些普通的HTML代码。到目前为止,我的努力还没有使图像移动。
document.addEventListener("DOMContentLoaded", function() {
var y = 0;
while (true) {
y -= 1;
document.getElementById("bgImg").left = y;
}
})#bgImg {
background-image: url("img1.jpg");
background-repeat: repeat-x;
width: 100%;
height: 660px;
display: inline;
}<div id="bgImg">
</div>
这只是冻结了我的浏览器,根本不滚动。很可能是因为“时间(真)”。
发布于 2019-08-16 19:03:14
这最好用CSS动画而不是JavaScript来完成。CSS键框动画被设计成在预置属性状态之间以最小的内存开销(并且没有同步的while循环:P)来循环平滑转换。
您需要添加的唯一信息是图像的宽度。如果您使用这个值作为background-position在动画的to状态中的x坐标,那么一旦背景移动到那么多像素,它就会跳回from位置。如果您已经正确设置了宽度,则此跳转将对查看器不可见。
#bg {
background: url('https://www.gravatar.com/avatar/e47523b278f15afd925a473e2ac0b966?s=120&d=identicon&r=PG&f=1');
background-repeat: repeat-x;
width: 240px;
height: 120px;
animation: bgScrollLeft 5s linear infinite;
}
@keyframes bgScrollLeft {
from {
background-position: 0 0;
}
to {
background-position: -120px 0;
}
}<div id="bg"></div>
发布于 2019-08-16 19:15:10
在看到你的问题后,我才在自己的网站上实现了这一点。好主意!
function animateBg(px=0){
requestAnimationFrame(()=>{
document.body.style.backgroundPosition = `${px}px 0px`;
animateBg(px+0.5);
});
}
animateBg();它假设您在CSS中设置了bg映像。更改0.5以更改速度。
发布于 2019-08-16 19:02:07
您正在向左移动元素,但实际上您应该移动您的背景位置。在它旁边有一个while(1)循环,它将无限运行。所以2任务,创建一个动画框架,不要运行无限。并更改背景位置属性。
var left = 0;
// You might want to add a time delta
function animate() {
requestAnimationFrame( animate );
document.getElementById("bgImg").style.backgroundPosition = '0 ' +left-- + 'px';
}
animate();注意,代码可能不起作用,但给出了解决方案的想法。
查看requestAnimationFrame,了解它所做的事情。
编辑
看看IronFlare解决方案,它使用css更漂亮。
https://stackoverflow.com/questions/57529787
复制相似问题