首页 > 解决方案 > javascript(根据正弦函数滚动页面循环)

问题描述

我不知道window.scrollTo选项中是否有持续时间,因为它都是 JSON 并且 API 没有在任何地方明确记录。

for (i = 0; i < 1000; i++) {
    var sine = Math.sin(i/10);
    var scroll = sine * 1000;
    console.log(scroll);
    window.scrollTo({top: scroll, left: 0, behavior: 'smooth' });
}

我想要一个页面连续上下滚动,但这似乎不起作用。它不像您想象的那样按顺序执行所有指令,而是控制所有值,然后在最后进行滚动。

JavaScript 中也没有明智的sleep功能。此外,此卷轴的持续时间完全是任意的。

我应该如何尝试在 JavaScript 中完成这样一个看似简单的任务?

我会考虑在伪代码中做这样的事情:

i = 0;
while (true) {
    scroll = sine(i);
    scrollTo(sine);
    // if scrollTo is asynchronous or something.
    sleep(x); // x how ever long scroll takes.
    i += 1;
}

但是sleepJS 中没有函数,执行的顺序也没有,不知道需要多长时间x

编辑:

仍然没有找到解决方案。

https://codepen.io/waterwaltz/pen/gbOdQb/

这个codepen演示了一种可能的方式,如下所示:

function loop() {
    $("html, body").animate({ scrollTop: "0" }, 1000).animate({scrollTop: "100"}, 1000, loop)
}

但是没有办法退出循环!因为 1)JS 全局变量根本不起作用 2)传递的变量也不起作用(没有参数的回调?谁编写了这种语言?)

我能找到的唯一一个可停止循环的例子是:

https://codepen.io/gabrieleromanato/pen/jEfbn

但它使用不滚动的 CSS 动画!

我喜欢 JavaScript!

编辑2:

情况更糟。

var thing = "GO";
window.setInterval(function() {
    console.log(thing);
    if (thing == "GO") {
        $("html, body").animate({ scrollTop: "0" },1000)
        $("html, body").animate({ scrollTop: "1000" },1000)
    }
});

thing在最初设置为的情况下运行它"GO"会导致滚动循环,甚至是 consoles "GO",但随后设置thing"NO"(或其他东西),不仅不会停止循环,"NO"还会在保持循环继续进行的同时进行控制台!

我现在完全不知所措。

标签: javascript

解决方案


这里有一个例子。这是一种方法。

尽管也可以通过持续执行该rAF函数requestAnimationFrame,然后检查作为参数传递给rAF(a DOMHighResTimestamp) 的时间。

var i = 0;

function doSinScroll(num) {
  var sine = Math.sin(num / 10);
  var scroll = sine * 1000;
  console.log(scroll);
  window.scrollTo({
    top: scroll,
    left: 0,
  });
}

function rAF() {
  doSinScroll(i++);
  if (i < 1000) {
    setTimeout(function() {
      window.requestAnimationFrame(rAF);
    }, 100);
  }
}

window.requestAnimationFrame(rAF);
.red,
.white {
  width: 100%;
  height: 128px;
}

.red {
  background-color: red;
}

.white {
  background-color: white;
}
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>
<div class="red">&nbsp;</div>
<div class="white">&nbsp;</div>


推荐阅读