原生方式实现swiper效果
在vue项目下 以组件形式导入使用即可
支持点击切换、滑动切换
思路
1、 写轮播牌子,数量若干,限定在一个盒子内 横向排列
2、写两组样式 一个是放大的 一个是缩小的
3、js监听鼠标落下和抬起事件
落下时记录offeset位置
抬起时计算位移距离
判断是否满足切换条件
将放大样式置于满足条件的元素
4、补齐css过渡动画
效果
<template>
<div>
<div
class="swip"
ref="swip"
@mousedown="inDown"
@mousemove="inMove"
@mouseup="inUp"
@mouseleave="inLeave"
>
<div class="btn leftBtn" @click="toLeft">《-</div>
<div class="btn rightBtn" @click="toRight">-》</div>
<div
class="swipInner"
ref="swipInner"
:style="{ width: total * 305 + 'px' }"
>
<div class="swips" v-for="i in total" :key="i">
<div
style="border-radius: 7px"
:class="current == i ? 'selected' : 'notSelected'"
></div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "swipInner",
components: {},
watch: {
current(val) {
this.$refs["swipInner"].style.left = 0 - (val - 2) * 305 + "px";
},
},
data() {
return {
total: 12,
current: 2,
promit: false,
initNumb: false,
perNumb: false,
};
},
mounted() {},
methods: {
inDown(e) {
this.promit = true;
this.initNumb = e.clientX;
this.$refs["swipInner"].style.transitionDuration = "unset";
},
inMove(e) {
if (this.promit) {
this.$refs["swipInner"].style.left =
Number(this.$refs["swipInner"].style.left.slice(0, -2)) +
(e.clientX - this.initNumb - this.perNumb || 0) +
"px";
this.perNumb = e.clientX - this.initNumb;
}
},
inUp() {
this.promit = false;
this.perNumb = false;
this.$refs["swipInner"].style.transitionDuration = "0.55s";
this.current = Math.floor(
0 - Number(this.$refs["swipInner"].style.left.slice(0, -2)) / 305 + 2
);
},
inLeave() {
this.promit = false;
this.perNumb = false;
this.$refs["swipInner"].style.transitionDuration = "0.55s";
this.current = Math.floor(
0 - Number(this.$refs["swipInner"].style.left.slice(0, -2)) / 305 + 2
);
},
toLeft() {
if (this.current > 1) {
this.current -= 1;
} else {
this.current = this.total;
}
},
toRight() {
if (this.current < this.total) {
this.current += 1;
} else {
this.current = 1;
}
},
},
};
</script>
<style lang="less" scoped>
.swip {
height: 280px;
width: 920px;
background-color: rgba(0, 0, 0, 0.1);
position: relative;
overflow: hidden;
.swipInner {
position: absolute;
left: 0;
top: 0;
background-color: rgba(255, 255, 40, 0.4);
transition-duration: 0.55s;
height: 280px;
}
.swips {
height: 280px;
width: 300px;
display: inline-block;
margin-left: 5px;
}
.selected {
height: 280px;
width: 300px;
background-color: aqua;
transition-duration: 0.25s;
}
.notSelected {
height: 240px;
margin-top: 20px;
width: 250px;
margin-left: 25px;
background-color: aqua;
transition-duration: 0.25s;
}
.btn {
height: 22px;
width: 22px;
background-color: rgba(255, 255, 255, 0.7);
position: absolute;
border-radius: 50%;
cursor: pointer;
top: calc(50% - 10px);
z-index: 10;
}
.leftBtn {
left: 10px;
}
.rightBtn {
right: 10px;
}
}
</style>
其他需求 自行优化修改