最近小米miui10即將上線,一直想使用手勢(shì)邊緣返回功能,使用小米Note3刷了miui10后,卻發(fā)現(xiàn)沒(méi)有全面屏手勢(shì)操作!!

在瀏覽某應(yīng)用的時(shí)候,發(fā)現(xiàn)了它也采用了類(lèi)似小米的返回功能,所以這里,也用vue自己寫(xiě)了一個(gè)。
功能需求:
1、要從屏幕邊緣向右滑動(dòng),其他地方不管用
2、上下滑動(dòng)時(shí),箭頭跟隨
3、向右劃出,逐漸突起,從透明變不透明,剪頭角度變化
4、劃出一定范圍后松開(kāi)觸發(fā)返回,沒(méi)達(dá)到范圍不觸發(fā)。
事件監(jiān)聽(tīng)
這里主要監(jiān)聽(tīng)touch事件,通過(guò)touchstart來(lái)判斷,是否是從邊緣滑入的;
通過(guò)touchmove監(jiān)聽(tīng)向右滑入的幅度,以及上下移動(dòng)的位置;
然后通過(guò)touchend監(jiān)聽(tīng)停止滑動(dòng)時(shí)的位置,觸發(fā)返回動(dòng)作。
主要代碼如下:
window.addEventListener('touchstart', this.touchstart)
window.addEventListener('touchmove', this.touchmove)
window.addEventListener('touchend', this.touchend)
相關(guān)方法
// 獲取坐標(biāo)
getXY(event) {
let touch = event.touches[0]
this.x = touch.clientX
this.y = touch.clientY
},
touchstart(event) {
this.getXY(event)
// 判斷是否是邊緣滑動(dòng)
if (this.x < 30) {
this.show = true
this.render()
} else {
this.show = false
}
},
touchmove(event) {
this.getXY(event)
this.render()
},
touchend() {
// 判斷停止時(shí)的位置偏移
if (this.x > 90 && this.show) {
this.$router.go(-1)
}
this.x = 0
this.show = false
},
事件是相對(duì)比較簡(jiǎn)單的,接下來(lái)是使用canvas來(lái)畫(huà)邊緣樣式。
邊緣樣式及動(dòng)畫(huà)

邊緣效果
Html
<template>
<canvas id="arrows" class="arrows" :style="style"></canvas>
</template>
Css
.arrows {
position: fixed;
width: 30px;
height: 210px;
left: -2px;
}
Js
computed: {
// 樣式計(jì)算屬性
style() {
return {
top: this.y - 100 + 'px', // 跟隨上下移動(dòng)
display: this.show ? 'block' : 'none'
}
}
},
mounted() {
let canvas = document.getElementById('arrows')
canvas.width = 30
canvas.height = 210
this.context = canvas.getContext('2d')
},
methods:{
render() {
let x = this.x / 3
if (x > 25) {
x = 25
}
let n = ~~(x / 5)
// 獲取顏色透明度
let color = `rgba(30,30,30,${x / 25})`
// 清空畫(huà)布
this.context.clearRect(0, 0, 30, 210)
this.context.fillStyle = color
this.context.beginPath()
this.context.moveTo(0, 0)
// 貝塞爾曲線,劃出弧度
this.context.bezierCurveTo(5, 70, x, 70, x, 100)
this.context.moveTo(x, 100)
this.context.bezierCurveTo(x, 140, 5, 140, 0, 210)
this.context.lineTo(0, 0)
this.context.fill()
// 箭頭
this.context.moveTo(2 * n, 93)
this.context.lineTo(3 * n, 100)
this.context.lineTo(2 * n, 107)
this.context.lineWidth = 2
this.context.strokeStyle = '#fff'
this.context.stroke()
}
}

關(guān)注我,查看更多分享