vue实现一个滚动条样式,博智网带你了解详细信息。

起初是想修改浏览器滚动条样式来达到效果 但是查阅了资料 浏览器滚动条不能修改宽度与位置 没办法只能自己写 首先是滚动条样式

<p class="scrollBar" v-if="roleList.length > 5">
        <p
          class="box"
          @mousedown="move"
          v-bind:style="{ width: activewidth + 'px' }"
        ></p>
      </p>

样式

.scrollBar {
  width: 500px;
  height: 6px;
  background: #d5dbf5;
  margin: 0 auto;
  margin-top: 72px;
  border-radius: 4px;
  position: relative;

  .box {
    width: 30px;
    height: 100%;
    background: #fff;
    border-radius: 4px;
    position: absolute;
    left: 0;
  }
  .box:hover {
    cursor: pointer;
  }
}

滚动区域的样式这里就不写了

1 首先是滚动条滑块的宽度

mounted() {
    //滚动区域宽度  我这里是遍历的user列表  所以我拿到列表的长度*每个li的宽度即为总宽度
    let bgWidth = this.$refs.liList.clientWidth * this.roleList.length;
    //可视区域宽度  1065   这个就是上图中白色背景盒子的宽度
    //滑块宽度 500为滚动条宽度  计算这个宽度是为了拿到滑块可以滑动的距离 这个下面会说到
    this.activewidth = 500 * (1065 / bgWidth);
  },

2 给滑块添加鼠标事件

move(e) {
      //获取目标元素
      let op = e.target;
      // ScrollArea
      //算出鼠标相对元素的位置
      let disX = e.clientX - op.offsetLeft;
      //滚动条可以滚动的距离
      let viewArea = 500 - this.activewidth;
      //滚动区域宽度
      let bgWidth = this.$refs.liList.clientWidth * this.roleList.length;
      document.onmousemove = (e) => {
        //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
        let left = e.clientX - disX;
        //left < 0 表示滑块已经到最左边
        //或者left > viewArea  表示滑块到最右边
        if (left < 0 || left > viewArea) {
          //console.log("到头了");
          //这个时候要清空事件 不然滑块就划出滚动条区域了
          document.onmousemove = null;
        } else {
         //滑块的滑动距离
          op.style.left = left + "px";
          //滚动区域的滑动距离 = 滚动区域宽度*(滑块滑动的距离/500)
          this.$refs.ScrollArea.style.left =
            "-" + bgWidth * left / 500 + "px";
        }
      };
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },

到此这篇关于vue实现一个滚动条样式的文章就介绍到这了,更多相关vue实现滚动条内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!