<template> <div id="SlideBar" class="container"> <div class="item" ref="slide" :style="slideStyle" @touchstart="start($event)" @touchmove="move($event)" @touchend="end($event)"> <img src="../../../assets/newimage/vip/levelb1.png" alt=""> </div> <div class="btn" ref="btn"> </div> </div> </template> <script> export default { name: 'SlideBar', props: { }, data() { return { // 屏幕总宽度 clientWidth: document.body.clientWidth, flag: false, startX: 0, endX: 0, slideStyle: { left: 0, transition: 'none' } } }, created: function() { }, methods: { start(e) { //记录开始滑动屏幕的X轴的位置 this.flag = true; this.startX = e.touches[0].clientX; console.log(e.touches[0].clientX) this.endX = this.$refs.slide.offsetLeft; console.log(this.$refs.slide.offsetLeft) this.slideStyle.transition = 'none'; }, move(e) { if (this.flag) { // 处理鼠标移动的逻辑 var moveX = this.endX + (e.touches[0].clientX - this.startX); //计算滑动的距离 if (Math.abs(moveX) >= this.$refs.btn.offsetWidth && moveX < 0) { //判断滑动的距离是否大于class:btn的宽度 moveX = (Math.abs(moveX) - this.$refs.btn.offsetWidth) * 0.1; // 0.3阻力系数 this.slideStyle.left = -this.$refs.btn.offsetWidth - moveX + 'px'; } else if (moveX >= 0) { //滑动距离是否大于等于0 this.slideStyle.left = 0 + 'px'; //大于等于0让class:item等于0 } else { this.slideStyle.left = moveX + 'px'; //小于0让class:item等于滑动的距离 } } }, end(e) { if (this.flag) { this.flag = false; var moveX = e.changedTouches[0].clientX - this.startX; //计算滑动的距离 this.slideStyle.transition = 'left .3s'; var btnWidth = this.$refs.btn.offsetWidth; //class:btn的宽度 if (moveX < 0) { if (Math.abs(moveX) >= btnWidth / 2 || Math.abs(this.$refs.slide.offsetLeft) >= this.$refs.btn .offsetWidth) { //是否大于class:btn宽度的一半 this.slideStyle.left = -btnWidth + 'px'; //左滑超过class:btn宽度的一半就滑回去 } else if (Math.abs(moveX) < btnWidth / 2) { //小于class:btn宽度的一半 this.slideStyle.left = 0 + 'px'; //左滑没有超过class:btn宽度的一半回原位 } } else if (moveX > 0 && this.endX != 0) { if (Math.abs(moveX) >= btnWidth / 2) { this.slideStyle.left = 0 + 'px'; //右滑超过class:btn宽度的一半就滑回去 } else if (Math.abs(moveX) < btnWidth / 2) { this.slideStyle.left = -btnWidth + 'px'; //右滑没有超过class:btn宽度的一半回原位 } } } } }, mounted() { var _this = this; // 使用js的现代事件监听transition过渡结束 this.$refs.slide.addEventListener('transitionend', function() { _this.endX = this.offsetLeft; }) } } </script> <style lang="scss" scoped> .container { position: relative; display: flex; flex-direction: column; justify-content: flex-start; align-items: stretch; background-color: #f0f2f5; .btn { height: 100%; position: absolute; right: 0; top: 0; background: red; display: flex; background: #258ac5; 4rem; height: 2rem; } .item { background: #b30000; padding: 0.2rem; display: flex; position: relative; background: #fff; z-index: 2; box-shadow: 0.02rem 0 0.05rem #ddd; height: 2rem; } } img { 2rem; height: 2rem; } </style>