vue2+h5横向滑动滚动及指示器样式

13 篇文章 0 订阅
4 篇文章 0 订阅

实现效果

大长图可以横向滑动滚动,并且滑动到最右边切换指示器
在这里插入图片描述

代码实现

实现逻辑:
1.将原有滑动条隐藏,
2.计算滑动盒子的宽度与屏幕宽度的差值,如果与滑动的距离无限接近,那就说明已经滑动到了最右边。
第一个指示器是控制css样式,第二个指示器是滑动效果

<template>
  <div>
    <div class="container">
      <div class="container-item">
       <img src="../../assets/tree.jpg" alt="">
      </div>
    </div>
    <div class="indicator">
        <span :class="{bgcolor:leftColor}" ></span>
        <span :class="{bgcolor:rightColor}"></span>
    </div>
    <!--指示器滑动的效果-->
    <div class="indicator">
        <div class="line"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'my-page',
  data () {
    return {
      leftColor: true,
      rightColor: false
    }
  },
  mounted () {
    const container = document.getElementsByClassName('container')[0]
    const myWidth = container.scrollWidth - container.clientWidth
    const indicator = document.querySelector('.indicator')
    const line = document.querySelector('.line')
    // console.log(myWidth, '盒子宽度减去屏幕宽度')
    container.addEventListener('scroll', () => {
      const newWidth = myWidth - container.scrollLeft
      // console.log(container.scrollLeft, newWidth, '超出的宽度减去滚动的距离')
      if (newWidth < 1) {
        // 滚动到了最右边
        this.rightColor = true
        this.leftColor = false
        // 滑动效果
        line.style.transform = `translateX(${indicator.scrollWidth - line.scrollWidth}px)`
      }
      if (container.scrollLeft === 0) {
        // 滚动到了最左边
        this.leftColor = true
        this.rightColor = false
        // 滑动效果
        line.style.transform = 'translateX(0px)'
      }
    })
  }
}
</script>

<style>
.container {
    width: 100%;
    height: 348px;
    overflow: scroll;
}
.container::-webkit-scrollbar {
  display: none;
}
.container-item{
  width: 929px;
  height: 100%;
}
.container-item img{
  width: 929px;
  height: 100%;
}
.indicator{
  width:80px;
  height:10px;
  border-radius: 5px;
  background-color: #ccc;
  margin: 20px auto;
  display: flex;
}
span{
  width:40px;
  height:10px;
  border-radius: 5px;
}
.bgcolor{
  background-color: pink;

}
.line{
  width:50px;
  height:10px;
  border-radius: 5px;
  background-color: pink;
  transition:all .3s
}
</style>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值