【问题标题】:How do I make an image endlessly repeat scroll in Javascript?如何在 Javascript 中使图像无休止地重复滚动?
【发布时间】:2019-08-16 18:54:59
【问题描述】:

我制作网页只是为了娱乐。我希望在第一次加载页面时背景图像无休止地向左滚动。图像在 CSS 中设置为 repeat-x,并且在端到端放置时是无缝的。我写的这段代码是否朝着正确的方向发展?

为了简单起见,我希望保留 JS vanilla,但如果 JQuery、CSS 或其他库能更好地处理这一点,我会全力以赴。

非常感谢您的帮助!

我已经在一个简单的 HTML 文档中尝试了一些普通的 JavaScript 代码。到目前为止,我的努力根本没有使图像移动。

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>

这只会冻结我的浏览器并且根本不滚动。可能要感谢“while(true)”。

【问题讨论】:

  • 不能说这将是解决方案,但也许看看requestAnimationFrame,所以你至少不要冻结浏览器

标签: javascript html animation scroll motion


【解决方案1】:

最好使用CSS animation 而不是 JavaScript。 CSS 关键帧动画旨在以最小的内存开销在预设的属性状态之间循环平滑过渡(并且没有同步 while 循环:P)。

您需要添加的唯一信息是图片的宽度。如果在动画的to 状态下将此值用作background-position 的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;
  }
}
&lt;div id="bg"&gt;&lt;/div&gt;

【讨论】:

  • 工作愉快;谢谢!作为一名应用程序/网络开发人员,我有点迷失了。图形和网络对我来说是另一个世界!非常感谢大家。
【解决方案2】:

您正在向左移动元素,但实际上您应该移动背景位置。旁边有一个 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 更漂亮。

【讨论】:

    【解决方案3】:

    看到您的问题后,我刚刚在自己的网站上实现了这一点。好主意!

    function animateBg(px=0){
        requestAnimationFrame(()=>{
            document.body.style.backgroundPosition = `${px}px 0px`;
            animateBg(px+0.5);
        });
    }
    animateBg();
    

    假设您在 CSS 中设置了背景图像。更改0.5以更改速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      相关资源
      最近更新 更多