前端学习之轮播图
<template>
<div class="body">
<div class="a">
<!--动态设置背景图片-->
<div class="b" :style="{'background-image':'url('++')'}">
</div>
<!--for循环-->
<div class="c">
<div :class="i === 0 ? 'd dd' : 'd'" v-for="(img,i) in srcs" @mouseover="mouseOver(i)">
<img :src="require('@/assets/shuffling/' + img)" alt="">
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Shuffling',
data () {
return {
srcs : [
"",
"",
"",
"",
""
],
bigImg: {
backgroundImg: ""
},
index : 0, //索引,默认选中数据
time: null, //轮播器
d: [], //所有设置为d的标签
}
},
methods: {
init() {
console.log("初始化")
this.index = 0;
//获取到d标签
this.d = document.getElementsByClassName("d");
//调用轮播器
this.ts();
},
//重置函数,将标签的名称重新设置为d
repeat() {
let length = this.d.length;
for (let i = 0; i < length; i++) {
this.d[i].className = 'd'
}
},
//选中函数
selected(i) {
//重置所有的标签
this.repeat()
//根据索引选中的标签设置为d dd
if (this.d[i]) {
this.d[i].className = 'd dd'
console.log("选中图片:" + i)
//设置图标
this.setImg(i)
}
},
//鼠标移动到图片上需要停止轮播器
mouseOver(i) {
//先设置大图
this.setImg(i)
//选中
this.selected(i)
//轮播器不为空时清除
if (this.time) {
clearInterval(this.time)
}
//跳过当前索引
this.index = i
this.index++
//继续设置轮播
this.ts()
},
//轮播函数
ts() {
//默认设置轮播函数,传入所有的 d 标签
this.time = setInterval(() => {
if (this.index >= 5) {
this.index = 0;
}
//设置选中图片
this.selected(this.index)
this.index++
}, 1500)
},
setImg(i) {
this.bigImg.backgroundImg = require(`@/assets/shuffling/${i+1}.jpg`)
}
},
created() {
//设置初始的图片信息
this.bigImg.backgroundImg = require("@/assets/shuffling/")
this.init()
}
}
</script>
<style scoped>
/*
设置背后body的背景颜色以及长宽高
设置布局模式:flex
内容展示为:居中
使用垂直居中需要设置:flex-wrap:wrap; 换行方式
*/
.body {
background-color: rgba(206, 182, 182, 0.637);
display: flex;
height: 100vh;
flex-wrap:wrap; /*设置了换行方式:(align-content: center; 垂直居中才有效果)*/
justify-content: center; /*水平居中*/
align-content: center; /*垂直居中*/
}
.a {
position: relative;
width: 650px;
height: 500px;
display: flex;
justify-content: space-evenly; /*b和c子元素之间留点空白*/
}
.b {
width: 400px;
height: 500px;
transition: .4s;
background-size: cover; /*背景图像扩展到足够大,图片的比例不会变,超过容器的部分会被裁掉*/
}
.c {
width: 200px;
height: 500px;
display: flex;
/* 纵向布局 */
flex-direction: column;
justify-content: space-between; /*平均分布,之间会有点空白*/
}
.d {
position: relative;
width: 200px;
height: 90px;
right: 0;
transition:.5s;
overflow: hidden; /*图片多余的部分隐藏起来*/
}
.d img {
position: absolute;
width: 200px;
transform: translate(0,-50px); /*可以对元素进行转换,旋转缩放,这里将图片展示上移50px*/
transition: .5s; /*给所有的img添加一个动画效果,完成动画效果需要的时间 500毫秒*/
right: 0; /*所有的img标签默认都靠右为0*/
}
/*页面一开始,dd的标签就开始执行动画效果 */
. {
opacity: 0;
right: 250px;
}
/*鼠标移动到 d下面 img标签,会设置透明离右边250px的距离隐藏起来,相当于一个左移的动画效果*/
.d:hover img {
opacity: 0;
right: 250px;
}
</style>