用 touchend 事件
const scrollContainer = ref<HTMLElement | null>(null)
const scrollItem = ref<HTMLElement[]>([])
// 总活动个数(有续贷活动数量加1)
const totalItems = computed(
() =>
scrollItem.value.length + (props.isShowEvent ? 1 : 0)
)
// 保存上次滚动距离
let prevScrollLeft = 0
// 滑动滚动条 banner保持左吸
const onTouchend = () => {
if (
!scrollContainer.value ||
scrollItem.value.length === 0
) {
return
}
// 活动index
let itemIndex = 0
// 父容器滑动距离
const scrollLeft = scrollContainer.value.scrollLeft
// 父容器宽度
const scrollWidth = scrollContainer.value.scrollWidth
const containerWidth = scrollContainer.value.clientWidth
// 兼容ios(解决滑动最左边和最右留白问题)
if (
scrollLeft < 0 ||
scrollLeft + containerWidth > scrollWidth
) {
return
}
// 单个容器宽度
const itemWidth = scrollItem.value[0].clientWidth
// banner间的距离
const compStyles = window.getComputedStyle(
scrollItem.value[0]
)
const marginWidth = parseFloat(compStyles.marginRight)
if (prevScrollLeft > scrollLeft) {
// 向右滑动
itemIndex = Math.floor(scrollLeft / itemWidth)
} else if (prevScrollLeft < scrollLeft) {
// 向左滑动
itemIndex = Math.min(
Math.ceil(scrollLeft / itemWidth),
totalItems.value - 1
)
} else {
return
}
// 滚动条移动距离
const slidingLeft =
itemIndex * itemWidth + marginWidth * itemIndex
prevScrollLeft = slidingLeft
scrollContainer.value.scrollTo({
left: slidingLeft,
behavior: 'smooth',
})
}