HTML中新加入了許多新的事件,但由於相容性的問題,許多事件都沒有廣泛的應用,接下來為大家介紹一些好用的行動端觸控事件: touchstart、touchmove、touchend。
介紹下面我們來簡單介紹一下這幾個事件:
這些觸控事件具有常見的dom屬性。此外,他們還包含著三個用於追蹤觸控的屬性:
每個touch物件包含的屬性如下:
了解了觸摸事件的特徵,那就開始緊張刺激的實戰環節吧
實戰下面我們來透過使用觸控事件來實現一個行動端可滑動的進度條
我們先進行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')constgressBtn = document.querySelector('.progress-btn')constgressm = 0監聽touchstart事件
progressBtn.addEventListener('touchstart', e => { let touch = e.touches[0] touchPoint = touch.clientX // 取得觸控的初始位置btnLeft = parseInt(getComputedStyle(progressBtn, null)['left'], 10 ) // 此處忽略IE瀏覽器相容性})監聽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值與進度條容器長度的比值,計算進度條的長度百分比})透過一系列的邏輯運算,我們的進度條已經基本實現了,但是發現了一個問題,當觸摸位置超出進度條容器時,會產生bug,我們再來做一些限制
if (btnLeftStyle > progressWrapperWidth) { btnLeftStyle = progressWrapperWidth } else if (btnLeftStyle < 0) { btnLeftStyle = 0}至此,一個簡單的行動端捲軸就實現了
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。