vue实现简单无缝滚动效果_vue.js

2022年4月25日09:06:52

本文实例为大家分享了vue实现简单无缝滚动的具体代码,供大家参考,具体内容如下

效果

实现思路

在vue中如何复制一份列表出来呢且不能丢失绑定的事件,很简单使用slot插槽,使用两个插槽我们就拥有了两个列表

<div class="listScroll" ref="box">
    <slot></slot>
    <slot></slot>
</div>

组件完整代码

<template>
  <div class="listScroll" ref="box">
    <slot></slot>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "listScroll",
  created() {},
  mounted() {
    //在盒子内容高度小于可视高度时不滚动
    if (this.boxHeight < this.ele0.clientHeight) {
      this.start(this.height);
      this.setEvet();
    } else {
      this.isScroll = false;
    }
  },
  props: {
    speed: {
      default: 1,
      type: Number,
    },
  },
  computed: {
    //第一个slot
    ele0() {
      return this.$refs.box.children[0];
    },
    //第二个slot
    ele1() {
      return this.$refs.box.children[1];
    },
    //盒子的可视高度
    boxHeight() {
      return this.$refs.box.clientHeight;
    },
  },
  data() {
    return {
      height: 0,
      isScroll: true,
    };
  },
  methods: {
    //鼠标移入停止滚动 移出继续滚动
    setEvet() {
      this.$refs.box.onmouseenter = () => {
        this.isScroll = false;
        // this.height = 0;
      };
      this.$refs.box.onmouseleave = () => {
        this.isScroll = true;
        this.$nextTick(() => {
          this.start(this.height);
        });
      };
    },
    //滚动方法
    start(height) {
      this.ele0.style = `transform:translateY(-${height}px);`;
      this.ele1.style = `height:${this.boxHeight}px;transform:translateY(-${height}px);overflow: hidden;`;
      if (height >= this.ele0.clientHeight) {
        this.height = 0;
      } else {
        this.height += this.speed;
      }
      if (!this.isScroll) return;
      window.requestAnimationFrame(() => {
        this.start(this.height);
      });
    },
  },
};
</script>

<style lang="less" scoped>
.listScroll {
  overflow: hidden;
}
.hover {
  overflow-y: auto;
}
.hide {
  display: none;
}
</style>

使用

<template>
  <div class="scroll">
    <list-scroll class="box" :speed="1">
      <div class="list">
        <div class="item" v-for="item in list" :key="item.xh">
          <span>{{ item.xh }}</span
          ><span>{{ item.label }}</span>
        </div>
      </div>
    </list-scroll>
  </div>
</template>

<script>
import ListScroll from "@/components/listScroll";
export default {
  name: "scroll",
  components: { ListScroll },
  data() {
    return {
      list: new Array(10)
        .fill(1)
        .map((s, i) => ({ xh: i + 1, label: "hello wrold" })),
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  height: 300px;
}
.list {
  padding: 0 10px;
  width: 300px;
  .item {
    display: flex;
    justify-content: space-between;
    padding: 5px 0;
    cursor: pointer;
    &:hover {
      background-color: #95a5a6;
    }
  }
}
</style>

至此一个简单的无缝滚动就完成了(vue2和vue3通用)

  • 作者:橡皮擦不掉的  
  • 原文链接:https://blog.csdn.net/ZuoZuoDangerou/article/details/123662676
    更新时间:2022年4月25日09:06:52 ,共 2259 字。