Demo 在线地址:
https://sx00xs.github.io/test/29/index.html
---------------------------------------------------------------
ide: vscode
文件格式:.vue
ps:淡入淡出效果未实现,需修改
解析:
需求:
- 5张图片,每隔2秒自动切换为下一张
- 鼠标移入,图片静止
鼠标移出,图片恢复定时切换
- 鼠标移到按钮,图片切换为按钮对应图片
- 图片切换时显示效果为淡入淡出
写一个辅助函数,接受一个参数(图片Index),将所有图片的current类去除掉, index对应图片添加current类
- 5张图片,每隔2秒自动切换为下一张
答:
默认显示第一张,2秒后切换为下一张
给每张图片设置一个index索引
使用setinterval,每2秒后将所有图片的item.isActive设置为false,递增 index,设置对应图片的isActive为真
- 鼠标移入,图片静止
鼠标移出,图片恢复定时切换
答:
鼠标移入时,销毁setinterval句柄
鼠标移出时,恢复interval
- 鼠标移到按钮,图片切换为按钮对应图片
答:
移到按钮,将按钮对应图片index传给辅助函数
- 图片切换时显示效果为淡入淡出
答:
图片包裹在transition组件中,设置class,自动应用
<template> <div class="box" @mouseover="handleBoxOver" @mouseout="handleBoxOut"> <transition-group tag="ul" name="fade" > <li v-for="pic in pics" :key="pic.src" :class="{current:pic.isActive}" data-index="pic.count"> <img :src="pic.src" v-if="pic.isActive" width="490" height="170"> </li> </transition-group> <ul class="count"> <li v-for="item in pics" :key="item.count" :class="{current:item.isActive}" @mouseover="handleCountOver(item.count)" > {{item.count+1}} </li> </ul> </div> </template> <script> import { setInterval, clearInterval } from ‘timers‘; export default { name:‘Navs‘, data(){ return{ index:0, timer:null, play:null, pics:[ { src:require(‘../assets/lesson4/01.jpg‘), isActive:true, count:0 }, { src:require(‘../assets/lesson4/02.jpg‘), isActive:false, count:1 }, { src:require(‘../assets/lesson4/03.jpg‘), isActive:false, count:2 }, { src:require(‘../assets/lesson4/04.jpg‘), isActive:false, count:3 }, { src:require(‘../assets/lesson4/05.jpg‘), isActive:false, count:4 }, ] } }, methods:{ handleBoxOver(){ clearInterval(this.play); }, handleBoxOut(){ this.auotPlay() }, auotPlay(){ var _this=this; this.play=setInterval(function(){ _this.index++; _this.index >= _this.pics.length && (_this.index=0); _this.show(_this.index) },2000) }, show(count){ this.index=count; for(var i=0;i<this.pics.length;i++) this.pics[i].isActive=false; this.pics[this.index].isActive=true; }, handleCountOver(count){ this.show(count) }, enter(el,done){ }, leave(el,done){ } }, created(){ this.auotPlay(); } } </script>
原文地址:https://www.cnblogs.com/sx00xs/p/11266148.html
时间: 2024-10-11 23:27:59