I'm trying to build a simple "mainly css" image carousel that uses scroll snapping but also has navigation buttons to control the currently viewed slide. The only solution I've found is to use scrollIntoView() on the target element, which does what I want, but it also always scrolls the target element to the top of the page. I want the target carousel to be magic%E
P粉9767371012024-03-27 18:41:09
Try adding block: 'nearest'
to your scrollIntoView options like this:
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', }); }); });