前言
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')const progressWrapperWidth = progressWrapper.offsetWidthlet touchPoint = 0let btnLeft = 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武林網。
新聞熱點
疑難解答