基于2个元素的纵向轮播

基于2个元素的纵向轮播

在开发过程中,我们经常会遇到纵向轮播,但是感觉网上的插件不是很好用,遂自己写了一个轮播,代码如下(基于vuejs):

//swiper.vue

<template>
  <div class="layer" :style="{ height: height + "px", width: width + "px" }">
    <template v-if="list.length == 0">
      <div class="content">暂无数据</div>
    </template>
    <template v-if="list.length == 1">
      <div class="content">{{ list[0] }}</div>
    </template>
    <template v-if="list.length > 1">
      <div class="content">{{ list[0] }}</div>
      <div class="content">{{ list[1] }}</div>
    </template>
  </div>
</template>
<script>
export default {
  name: "swiper",
  data() {
    return {
      timer: null
    };
  },
  props: {
    list: {
      type: Array,
      default: () => {}
    },
timespace:{
type: Number,
default: 3000
}, height: { default: 30, type: Number }, width: { default: 300, type: Number } }, watch: { list: { immediate: true, handler: function(nv, ov) { if (nv.length > 1) { this.$nextTick(() => { this.multiples(1); }); } } } }, methods: { multiples(d) { let dom = document.getElementsByClassName("content")[0]; let layer = document.getElementsByClassName("layer")[0]; let deg = 0; let index = d; if (this.timer) { clearInterval(this.timer); this.timer = null; } this.timer = setInterval(() => { deg = this.height; index++; dom.style.marginTop = `${-deg}px`; setTimeout(() => { let newdom = dom.cloneNode(true); layer.removeChild(dom); newdom.style.marginTop = `0px`; let textindex = index % this.list.length; newdom.innerHTML = this.list[textindex]; layer.appendChild(newdom); dom = document.getElementsByClassName("content")[0]; if (index == this.list.length) { clearInterval(this.timer); this.multiples(0); return false } }, 300); }, this.timespace); } } }; </script> <style scoped> .layer { width: 300px; height: 30px; background: rgba(0, 0, 0, 0.1); box-sizing: border-box; overflow: hidden; } .content { height: 100%; line-height: 30px; transition: all 0.2s linear; } </style>

  原理: 类似于人走路一样,只需要两只脚,便可行万里路,生成一个元素,当隐藏掉的时候,删除这个元素,后续再新增元素来补位

父组件:

...
<swiper :list="list"></swiper>
....
data(){
  return {
    list: ["第一个元素","第二个元素","第3个元素","第4个元素"]
  }
}

 效果(已加速3倍):

 

原文链接:https://www.cnblogs.com/tony-stark/archive/2021/07/21/15041498.html