如何链接多个javascript`scroll()`?

问题描述 投票:0回答:1

我有一个像这样的页面和脚本:

我想滚动到每个

listitem
暂停一秒钟,然后滚动到下一个
listitem
等等。

我尝试的代码如下所示:

const sleep = (time) => new Promise(res => setTimeout(res, time, "done sleeping"));


let elm = document.querySelector('#pane-side');
let listitems = elm.children[0].children[0].children
for (let index = 0; index < listitems.length; index++) {
  const y = listitems[index].getBoundingClientRect().top + window.scrollY;
  elm.scroll({
    top: y,
    behavior: 'smooth'
  });
  sleep(1000).then(msg => console.log(msg));
}
<div id="pane-side">
  <div>
    <div>
      <div>
        <div role="listitem"></div>
        <div role="listitem"></div>
        <div role="listitem"></div>
        <div role="listitem"></div>
        <div role="listitem"></div>
        <div role="listitem"></div>
        <div role="listitem"></div>
      </div>
    </div>
  </div>
</div>

它只滚动一次到第一个

listitem
,然后什么都不做。

我尝试的另一个变体是将

elm.scroll({..})
替换为
listitems[index].scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
,它甚至没有滚动一次。

javascript html scroll
1个回答
0
投票

实现此目的的一种方法是使用通过

setTimeout()
递归调用的函数,每次调用都会增加索引。请注意,您可以使用模运算符来确保索引永远不会超出范围。

let elm = document.querySelector('#pane-side');
let listitems = elm.children[0].children[0].children[0].children;

const scrollToItem = index => {
  listitems[index % listitems.length].scrollIntoView({
    behavior: "smooth",
    block: "end",
    inline: "nearest"
  });
  setTimeout(() => scrollToItem(++index), 1000);
}
scrollToItem(0);
div[role] {
  height: 500px;
  font: 40px arial bold;
}
<div id="pane-side">
  <div>
    <div>
      <div>
        <div role="listitem">1</div>
        <div role="listitem">2</div>
        <div role="listitem">3</div>
        <div role="listitem">4</div>
        <div role="listitem">5</div>
        <div role="listitem">6</div>
        <div role="listitem">7</div>
      </div>
    </div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.