自制简单的range(Vue)

1,772 阅读3分钟

自制简单的range(Vue)

废话不多说先上成果图
实现思路

主要分界面与逻辑两大块

界面分为5个部分

  • 左滑块长度
  • 左内容位置
  • 中间长度
  • 右滑块长度
  • 右内容位置

逻辑

  • touch3个事件
  • 各滑块长度及位置计算
  • 选中时变色
具体实现步骤
  1. 首先我们明白整个容器的长度是不变的等于左边+中间+右边所以我们可以通过先获取总的容器的宽度并用变量进行保存,这里我用的就是屏幕的宽度。
this.rangeWidth = document.body.clientWidth
  1. 添加vue的三种touch事件
 @touchstart.stop.prevent="leftTextTouchStart" //按下
 @touchmove.stop.prevent="leftTextTouchMove" //滑动
 @touchend.stop.prevent="leftTextTouchEnd"  //松开

//右滑块,同上
 @touchstart.stop.prevent="rightTextTouchStart"
 @touchmove.stop.prevent="rightTextTouchMove"
 @touchend.stop.prevent="rightTextTouchEnd"
  1. 使用类绑定的方式,在touchStart事件触发的方式,修改点击的滑块的样式,在松开时触发touchend事件,恢复原来的样式
//滑动事件方法
 leftTextTouchStart() {
     this.leftClick = true;
 },
 leftTextTouchEnd() {
     this.leftClick = false;
 },
//类样式绑定
:class="{check_text_div:leftClick}"
  1. 滑动时三大块核心宽度及位置的计算,因为滑动中坐标轴是实时变化,这里我们使用vue的计算属性进行操作
rangeWidth //整个容器的宽度
leftWidth //左边滑动的距离,通过滑动事件定义
rightWidth //右边滑动的距离,通过滑动事件定义
width() {
    return Math.min(Math.max(0this.rangeWidth - this.leftWidth - this.rightWidth), this.rangeWidth)//内容宽度应等于总宽度减去左右两边,且大于等于0小于等于总宽度
},
left() {
    return Math.max(this.leftWidth, 0)//防止左滑出界面
},
right() {
    if (this.left + this.rightWidth <= this.rangeWidth) return Math.max(this.rightWidth - 0.50)//防止右滑出界面
},
  1. 滑动事件中,界面变化及左右两边滑动距离的记录
leftTextTouchMove(e) {
    let touch = e.changedTouches[0];
    let clientX = touch.clientX;//获取滑动事件的横坐标值
    if (clientX >= 0) {//只检测滑块在坐标值在屏幕内
        if (this.left + this.right <= this.rangeWidth) {//防止左右滑块位置倒置
            this.leftWidth = clientX;//左滑块距离等于x坐标
            //界面操作
            $('#nowRange').css({'left'this.left, 'width'this.width});
            $('#leftText').css({'left'this.left});
            $('#leftImg').css({'left'this.left});
       }
    }
},
rightTextTouchMove(e) {
    let touch = e.changedTouches[0];
    let clientX = touch.clientX;//获取滑动事件的横坐标值
    if (clientX <= this.rangeWidth) {//只检测滑块在坐标值在屏幕内
        this.rightWidth = this.rangeWidth - clientX;//右边滑块距离等于总长度减去滑动横坐标
        if (this.left + this.right <= this.rangeWidth) {//防止左右滑块位置倒置
            //界面变化
            $('#nowRange').css({'width'this.width});
            $('#rightText').css({'right'this.right});
            $('#rightImg').css({'right'this.right});
        }
    }
},

6.文本内容通过计算值便可实现

leftText() {
    let num = parseInt(this.left / this.rangeWidth * 100);
    if (num === 0 || isNaN(num)) return '不限';
    return num + 'k';
},
rightText() {
    if (this.rangeWidth === 0return '不限';
    let num = parseInt((this.rangeWidth - this.right) / this.rangeWidth * 100);
    if (num >= 0) {
        if (num === 100return '不限';
        return num + 'k';
    }
}

核心代码就这些了,撒花完结,优化什么的,你们自己看着来咯

这是我的github,欢迎大佬们猛戳,不定时更新