滑動頭部固定,要不也瞭解下?
摘要:
廢話不多說先上成果圖
實現思路
主要分介面與邏輯兩大塊
介面分為5個部分
左滑塊長度
左內容位置
中間長度
右滑塊長度
右內容位置
邏輯
touch3個事件
各滑塊長度及位置計算
選中時變色
...
廢話不多說先上成果圖
實現思路
主要分介面與邏輯兩大塊
介面分為5個部分
- 左滑塊長度
- 左內容位置
- 中間長度
- 右滑塊長度
- 右內容位置
邏輯
- touch3個事件
- 各滑塊長度及位置計算
- 選中時變色
具體實現步驟
- 首先我們明白整個容器的長度是不變的等於左邊+中間+右邊所以我們可以通過先獲取總的容器的寬度並用變數進行儲存,這裡我用的就是螢幕的寬度。
this.rangeWidth = document.body.clientWidth
- 新增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"
- 使用類繫結的方式,在touchStart事件觸發的方式,修改點選的滑塊的樣式,在鬆開時觸發touchend事件,恢復原來的樣式。
//滑動事件方法 leftTextTouchStart() { this.leftClick = true; }, leftTextTouchEnd() { this.leftClick = false; },//類樣式繫結 :class="{check_text_div:leftClick}"
- 滑動時三大塊核心寬度及位置的計算,因為滑動中座標軸是實時變化,這裡我們使用vue的計算屬性進行操作。
rangeWidth //整個容器的寬度 leftWidth //左邊滑動的距離,通過滑動事件定義 rightWidth //右邊滑動的距離,通過滑動事件定義 width() { return Math.min(Math.max(0, this.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.5, 0)//防止右滑出介面 },
- 滑動事件中,介面變化及左右兩邊滑動距離的記錄。
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}); } } },
- 文字內容通過計算值便可實現。
leftText() { let num = parseInt(this.left / this.rangeWidth * 100); if (num === 0 || isNaN(num)) return '不限'; return num + 'k'; }, rightText() { if (this.rangeWidth === 0) return '不限'; let num = parseInt((this.rangeWidth - this.right) / this.rangeWidth * 100); if (num >= 0) { if (num === 100) return '不限'; return num + 'k'; } }