做了一个轮播图,可以自动切换,鼠标放上去后停止,左右切换是用element ui加上去的,箭头间距不一样有点难受,之后再看吧,记录一下。 把宽高调成一致,删掉i里面的padding,或者把样式改成饿了么官方的圆按钮间距就一样了。最近毕业比较忙,先这样吧。做无缝轮播图可以参考下我主页用原生写的那个。
下面是html的图和按钮部分 v-for中必须要写index作为:key的值。button应该卸载img后面,写在前面的会被img遮住,加个z-index:1,调高图层就可以了。
<div id="window">
<div class="cycle"
@mouseenter="stop"
@mouseleave="start" >
<div class="content" :style="changePic">
<img
v-for="(img_url, key) in img_src"
:key="key"
ref="imgs"
:src="img_url.url"
alt="这是轮播图"
/>
</div>
<div class="btn">
<button class="left" @click="go(1)" href="#">
<p>向左</p>
</button>
<button class="right" @click="go(-1)" href="#">
<p>向右</p>
</button>
</div>
<div class="bottom">
<span
v-for="(li, key) in img_src"
:key="key"
:class="{ active: key === index }"
>
</span>
</div>
</div>
</div>
</template>
这是数据,有一个点是,我本来是把img_src用数组写的,但是发现无法显示本地,打开工具提示找不到路径,只有网图可以显示。本地的图要以对象数组的形式写成这样。
学完后回过头来看开始明白是什么原因了,图片会被vue内置的webpack当做是一个资源模块来加载,所以要用commonJs的语法来写。
img_src: [
{ url: require("../../assets/img/1.jpg") },
{ url: require("../../assets/img/2.jpg") },
{ url: require("../../assets/img/3.jpg") },
],
index: 0, //现在是第几张
time: 1500, //设置循环时间
width: 0, //移动的长度
这是点击和自动轮播的方法
computed: {
changePic() {
return {
transform: `translate3d(${this.width}px, 0, 0)`, //主要实现核心
};
},
},
methods: {
stop() {
clearInterval(this.timer);
},
start() {
this.timer = setInterval(() => {
this.go(-1), console.log("开始计时");
}, 1000);
},
go(direc) {
console.log(direc);
if (direc == -1) {
this.index = this.index >= this.img_src.length - 1 ? 0 : this.index + 1;
} else if (direc == 1) {
this.index = this.index <= 0 ? this.img_src.length - 1 : this.index - 1;
}
console.log("index:", this.index);
this.move(); //移动
},
move() {
this.width = -400 * this.index;
console.log("width:", this.width);
},
},
在挂载构后调用定时器,销毁之前停止
mounted(){
console.log('挂载完成');
this.start();
},
beforeDestroy() {
this.stop();
},
css的样式,calc也踩坑了,要在运算符的两边加上空格,运算数值加上px才能起效
#window {
width: 100%;
}
.cycle {
width: 400px;
height: 300px;
position: relative;
top: 0;
left: 0;
margin: 0 auto;
z-index: 10;
overflow: hidden;
}
.content {
display: flex;
height: 100%;
transition: 0.5s ease;
}
.content img {
width: 400px;
border-radius: 10px;
}
.cycle button {
width: 40px;
height: 80px;
position: absolute;
top: 50%;
transform: translateY(-50%);
opacity: 0.5;
text-align: center;
}
.cycle .right {
right: 0px;
}
.cycle .left {
left: 0px;
}
.bottom {
position: absolute;
bottom: 10px;
display: inline-block;
transform: translateX(50%);
right: 50%;
}
.bottom span {
width: 14px;
height: 14px;
border-radius: 7px;
background-color: rgba(110, 102, 102, 0.849);
opacity: 0.4;
margin: 10px;
display: inline-block;
/* span是行内元素 */
}
/* 圆圈圈激活后*/
.bottom .active {
/*数值分别是:水平偏移,上下偏移,模糊,大小,颜色 */
box-shadow: 0px 0px 2px 2px #53a8ff;
background-color: #a0cfff !important;
opacity: 0.6;
}