我在 svelte 中创建了一个滑块组件,它在列表中显示许多产品卡。由于我在容器的 CSS 中添加了“scroll-snap-type: x强制”,因此当单击滚动条中的右/左按钮时,卡片会对齐。
如何模拟单击滚动条左/右箭头作为自定义导航按钮?设置滚动条位置不会解决问题。
+page.svelte
<SliderProducts>
{#each data.productsFeaturedData as product}
<ProductCard product={product}/>
{/each}
</SliderProducts>
SliderProducts.svelte
<script lang="ts">
import Flex from '../atoms/Flex.svelte';
import ButtonNavigation from '../molecules/ButtonNavigation.svelte';
$: innerWidth = 0;
$: containerWidth = 0;
$: marginOffset = (innerWidth - containerWidth) / 2 + 8;
const navigateSlider = (x: MouseEvent) => {
if (x.target) {
const element = x.target as HTMLButtonElement;
const direction = element.dataset.direction;
// TODO: Implement button navigation
console.log(direction);
}
};
</script>
<svelte:window bind:innerWidth />
<div class="slider-products">
<div class="container" bind:clientWidth={containerWidth}>
<h2>Trending in Shoes</h2>
<div class="button-navigation__container">
<ButtonNavigation direction="left" on:click={navigateSlider} />
<ButtonNavigation direction="right" on:click={navigateSlider} />
</div>
</div>
<div class="slider-container">
<Flex type="row" vAlign="top" colGap={true}>
<div
class="slider-track"
style="margin-left: {marginOffset}px; padding-right: {marginOffset}px;"
>
<slot />
</div>
</Flex>
</div>
</div>
不要手动调整滚动位置,请考虑使用
scrollBy
或 scrollTo
const container = document.querySelector('.slider-track');
const scrollAmount = container.clientWidth; // adjust as needed
const navigateSlider = (x: MouseEvent) => {
const direction = (x.target as HTMLButtonElement).dataset.direction;
if (direction === 'left') {
container.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
} else if (direction === 'right') {
container.scrollBy({ left: scrollAmount, behavior: 'smooth' });
}
};