让我们想象一个动态插入从服务器获取数据的内容的例子。它的目的是把它像一堆物品一样显示在一个卷轴抓取的容器中。
问题是浏览器会随机地尝试滚动到某个元素,但是不管插入多少元素,我都希望容器停留在第一个元素上。唯一的例外是手动滚动容器的用户。
除非我添加了scroll-snap属性,否则它可以正常工作。
下面是代码片段
const startingIdx = 3;
const batchSize = 10;
const delay = 500;
const root = document.querySelector('.pills');
const appendBatch = (from) => {
for(let i = 0; i < batchSize; i++){
const element = document.createElement('div');
element.classList.add('pill');
element.innerText = String(from + i);
root.appendChild(element);
}
}
for(let i = 0; i < 3; i++){
setTimeout(() => appendBatch(startingIdx + i*batchSize), i*delay);
}.pills {
display: flex;
gap: 20px;
width: 100%;
overflow: auto;
scroll-snap-type: x mandatory;
}
.pill {
width: 120px;
height: 40px;
background: rgba(92, 138, 255, 0.15);
display: flex;
align-items: center;
justify-content: center;
border-radius: 20px;
flex-shrink: 0;
scroll-snap-align: start;
}<main>
<div class="pills">
<div class="pill">1</div>
<div class="pill">2</div>
</div>
</main>
以及您可以自己复制它的演示:https://977940.playcode.io/
这就是我要说的

发布于 2022-10-05 11:42:05
把它加到你的剧本里。加载页面时,它会滚动到左侧。
window.addEventListener("DOMContentLoaded", () => {
root.scrollLeft = 0;
});发布于 2022-10-05 11:48:16
似乎在每次插入批处理之前添加scroller.scrollBy(0,0);会节省时间,因为它会迫使浏览器切换到现有元素。
https://stackoverflow.com/questions/73959601
复制相似问题