移动端 banner滑动

用 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',
    })

  
  }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值