短視頻源碼vue做一個簡單的動態輪播圖

html

<div class="banner">
  <ul class="con" :style="classobj">
     <li v-for="(item, index ) in banList" :key="index">
       <a :href="item.serviceContent">
         <img :src="item.imgUrl" alt="">
       </a>
     </li>
   </ul>
   <ul class="btn">
     <li v-for="(item, index) in banList" :key="index" @click="now(index)"></li>
   </ul>
   <div class="rb" @click="rb">></div>
   <div class="lb" @click="lb"><</div>
 </div>

javascript

export default {
 data () {
    return {
      banList: [], // banner列表
	  num: 0, // 當前圖片位置
    }
  },
  methods: {
    // 動態獲取圖片信息, 發送請求獲取數據庫數據
    async getBanner () {
      let res = await axios.getTest('xxx')
      if (res.code == 0) {
        this.banList = res.data.resultList
        // 判斷一下, 如果只有一張圖片就不自動播放輪播
        if (this.banList.length > 1) {
          this.startMove()
        }
      }
    },
    // 點擊小圓點
    now(index){
			this.num=index;
			console.log(this.num)
		},
    // 右移
		rb(){
			// 判斷是否到最後一張圖
			if(this.num == this.banList.length -1){
				this.num=0;
			}else{
				this.num++;
			}						
		},
    // 左移
		lb(){
			// 判斷是否到第一張圖
			if(this.num == 0){
				this.num = this.banList.length -1;
			}else{
				this.num --;
			}												
		},
    // 定時輪播
    startMove () {
      setInterval(() => {
        this.rb()
      }, 3000)
    }
  },
  created () {
    this.getBanner()
  },
  computed: {
  // 根據數據個數 動態計算 輪播的父盒子寬度
    classobj: function(){
		return { marginLeft: this.num * -7.5 + 'rem', width: this.banList.length * 7.5 + 'rem' }
		}	
  }
}
</script>

css
這裏我是用的是less

ul , li {
	list-style: none;
}
.banner{
	width: 7.5rem;
	height: 2.85rem;
	margin: 0 auto;
	position: relative;
	overflow: hidden;
}
.con{
	width: 37.5rem;
	height: 2.85rem;
	transition: 1s all;
}
.con li{
	width: 7.5rem;
	height: 2.85rem;
	float: left;
	overflow: hidden;
	padding: 0.2rem 0.25rem;
	line-height: 2.62rem;
}
.btn{
	position: absolute;
	bottom: 0.3rem;
	left: 50%;
	transform: translate(-50%, 0);
}
.btn li{
	width: 0.2rem;
	height: 0.2rem;
	border-radius: 50%;
	background: #fff;
	float: left;
	margin: 0.1rem;
	text-align: center;
}
.rb,.lb{
	display: block;// 不需要左右箭頭可以設爲 none
	position: absolute;
	font-size: 30px;
	color: orange;
	top: 50%;
	transform: translate(0 , -50%);
	margin-top: -20px;
}
.rb{
	right: 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章