css 如何阻止scrollIntoView()将容器滚动到页面顶部?

fcg9iug3  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(340)

我试图构建一个简单的、“大部分是css”的图像轮播,它使用scroll-snap,但也有导航按钮来控制当前视图中的幻灯片。(),它做了我想做的事情,但是它总是把目标元素滚动到页面的顶部。我想让目标carousel幻灯片和容器保持在原来的位置,我只想让幻灯片水平滚动到视图中。我正在看Adam阿盖尔的一个例子,他就是这样做的,容器保持在原来的位置,我看不出他的演示有什么不同。
我做了一个密码笔来演示。
https://codepen.io/krjo-the-decoder/pen/dyjPrLy
单击底部的编号按钮将正确滚动到右侧幻灯片,但也会将整个容器向上滚动到页面。
我尝试在scrollIntoView()之前和之后使用scrollTo()将容器的y轴滚动设置为它的现有位置,但没有效果。

<!-- Using tailwind.css -->
<div class="py-48 bg-gray-200">
  <h1 class="text-center font-bold mb-5 text-2xl">Scroll-snap Carousel</h1>
  <div class="grid grid-flow-col overflow-x-auto snap-x snap-mandatory overscroll-x-contain auto-cols-[100%] mx-auto w-[500px]">
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
  </div>
  <nav class="flex justify-center mt-4">
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="0">1</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="1">2</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="2">3</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="3">4</button>
  </nav>
</div>

<script>
const slides = document.querySelectorAll('[data-slide]');
document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', event => {
    console.log('event',event);
    slides[event.target.dataset.index].scrollIntoView({
      behavior: 'smooth',
      inline:   'center',
    });
  });
});
</script>
nle07wnf

nle07wnf1#

尝试将block: 'nearest'添加到scrollIntoView选项中,如下所示:

document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', event => {
    console.log('event',event);
    slides[event.target.dataset.index].scrollIntoView({
      behavior: 'smooth',
      inline:   'center',
      block:    'nearest',
    });
  });
});

相关问题