我正在嘗試構(gòu)建一個(gè)簡(jiǎn)單的“主要是 css”圖像輪播,它使用滾動(dòng)捕捉,但也有導(dǎo)航按鈕來(lái)控制當(dāng)前查看的幻燈片。我找到的唯一解決方案是在目標(biāo)元素上使用scrollIntoView(),它可以滿(mǎn)足我的要求,但它也總是將目標(biāo)元素滾動(dòng)到頁(yè)面頂部。我希望目標(biāo)輪播幻燈片和容器保持在原來(lái)的位置,并且我只希望幻燈片水平滾動(dòng)到視圖中。我正在看 Adam Argyle 的一個(gè)示例,他就是這樣做的,并且容器保持在原來(lái)的位置,我不知道他的演示有什么不同。
我做了一個(gè)codepen來(lái)演示。
https://codepen.io/krjo-the-decoder/pen/dyjPrLy
單擊底部的編號(hào)按鈕將正確滾動(dòng)到右側(cè)幻燈片,同時(shí)也會(huì)將整個(gè)容器在頁(yè)面上滾動(dòng)。
我嘗試在scrollIntoView()之前和之后使用scrollTo()將容器的y軸滾動(dòng)設(shè)置為其現(xiàn)有位置,但這沒(méi)有效果。
<!-- 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>
嘗試將 block: 'nearest'
添加到你的scrollIntoView選項(xiàng)中,如下所示:
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', }); }); });