前言
HTML中新添加了許多新的事件,但由于兼容性的問題,許多事件都沒有廣泛的應(yīng)用,接下來為大家介紹一些好用的移動端觸摸事件: touchstart、touchmove、touchend。
介紹
下面我們來簡單介紹一下這幾個事件:
- touchstart: 當手指觸摸屏幕時候觸發(fā),即使已經(jīng)有一個手指放在屏幕上也會觸發(fā)。
- touchmove:當手指在屏幕上滑動的時候連續(xù)地觸發(fā)。在這個事件發(fā)生期間,調(diào)用preventDefault()事件可以阻止?jié)L動。
- touchend:當手指從屏幕上離開的時候觸發(fā)。
這些觸摸事件具有常見的dom屬性。此外,他們還包含著三個用于跟蹤觸摸的屬性:
- touches:表示當前跟蹤的觸摸操作的touch對象的數(shù)組。
- targetTouches:特定于事件目標的Touch對象的數(shù)組。
- changeTouches:表示自上次觸摸以來發(fā)生了什么改變的Touch對象的數(shù)組。
每個touch對象包含的屬性如下:
- clientX:觸摸目標在視口中的x坐標。
- clientY:觸摸目標在視口中的y坐標。
- pageX:觸摸目標在頁面中的x坐標。
- pageY:觸摸目標在頁面中的y坐標。
- screenX:screenX:觸摸目標在屏幕中的x坐標。
- screenY:screenX:觸摸目標在屏幕中的x坐標。
- identifier:標識觸摸的唯一ID。
- target:screenX:觸摸目標在屏幕中的x坐標。
了解了觸摸事件的特征,那就開始緊張刺激的實戰(zhàn)環(huán)節(jié)吧
實戰(zhàn)
下面我們來通過使用觸摸事件來實現(xiàn)一個移動端可滑動的進度條
我們先進行HTML的布局
<div class="progress-wrapper">
<div class="progress"></div>
<div class="progress-btn"></div>
</div>
CSS部分此處省略
獲取dom元素,并初始化觸摸起點和按鈕離容器最左方的距離
const progressWrapper = document.querySelector('.progress-wrapper')
const progress = document.querySelector('.progress')
const progressBtn = document.querySelector('.progress-btn')
const progressWrapperWidth = progressWrapper.offsetWidth
let touchPoint = 0
let btnLeft = 0
監(jiān)聽touchstart事件
progressBtn.addEventListener('touchstart', e => {
let touch = e.touches[0]
touchPoint = touch.clientX // 獲取觸摸的初始位置
btnLeft = parseInt(getComputedStyle(progressBtn, null)['left'], 10) // 此處忽略IE瀏覽器兼容性
})
監(jiān)聽touchmove事件
progressBtn.addEventListener('touchmove', e => {
e.preventDefault()
let touch = e.touches[0]
let diffX = touch.clientX - touchPoint // 通過當前位置與初始位置之差計算改變的距離
let btnLeftStyle = btnLeft + diffX // 為按鈕定義新的left值
touch.target.style.left = btnLeftStyle + 'px'
progress.style.width = (btnLeftStyle / progressWrapperWidth) * 100 + '%' // 通過按鈕的left值與進度條容器長度的比值,計算進度條的長度百分比
})
通過一系列的邏輯運算,我們的進度條已經(jīng)基本實現(xiàn)了,但是發(fā)現(xiàn)了一個問題,當觸摸位置超出進度條容器時,會產(chǎn)生bug,我們再來做一些限制
if (btnLeftStyle > progressWrapperWidth) {
btnLeftStyle = progressWrapperWidth
} else if (btnLeftStyle < 0) {
btnLeftStyle = 0
}
至此,一個簡單的移動端滾動條就實現(xiàn)了
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。