前言
HTML中新添加了許多新的事件,但由于兼容性的問(wèn)題,許多事件都沒(méi)有廣泛的應(yīng)用,接下來(lái)為大家介紹一些好用的移動(dòng)端觸摸事件: touchstart、touchmove、touchend。
介紹
下面我們來(lái)簡(jiǎn)單介紹一下這幾個(gè)事件:
這些觸摸事件具有常見(jiàn)的dom屬性。此外,他們還包含著三個(gè)用于跟蹤觸摸的屬性:
每個(gè)touch對(duì)象包含的屬性如下:
了解了觸摸事件的特征,那就開(kāi)始緊張刺激的實(shí)戰(zhàn)環(huán)節(jié)吧
實(shí)戰(zhàn)
下面我們來(lái)通過(guò)使用觸摸事件來(lái)實(shí)現(xiàn)一個(gè)移動(dòng)端可滑動(dòng)的進(jìn)度條
我們先進(jìn)行HTML的布局
<div class="progress-wrapper"> <div class="progress"></div> <div class="progress-btn"></div></div>
CSS部分此處省略
獲取dom元素,并初始化觸摸起點(diǎn)和按鈕離容器最左方的距離
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監(jiān)聽(tīng)touchstart事件
progressBtn.addEventListener('touchstart', e => { let touch = e.touches[0] touchPoint = touch.clientX // 獲取觸摸的初始位置 btnLeft = parseInt(getComputedStyle(progressBtn, null)['left'], 10) // 此處忽略IE瀏覽器兼容性})監(jiān)聽(tīng)touchmove事件
progressBtn.addEventListener('touchmove', e => {e.preventDefault() let touch = e.touches[0] let diffX = touch.clientX - touchPoint // 通過(guò)當(dāng)前位置與初始位置之差計(jì)算改變的距離 let btnLeftStyle = btnLeft + diffX // 為按鈕定義新的left值 touch.target.style.left = btnLeftStyle + 'px' progress.style.width = (btnLeftStyle / progressWrapperWidth) * 100 + '%' // 通過(guò)按鈕的left值與進(jìn)度條容器長(zhǎng)度的比值,計(jì)算進(jìn)度條的長(zhǎng)度百分比})通過(guò)一系列的邏輯運(yùn)算,我們的進(jìn)度條已經(jīng)基本實(shí)現(xiàn)了,但是發(fā)現(xiàn)了一個(gè)問(wèn)題,當(dāng)觸摸位置超出進(jìn)度條容器時(shí),會(huì)產(chǎn)生bug,我們?cè)賮?lái)做一些限制
if (btnLeftStyle > progressWrapperWidth) { btnLeftStyle = progressWrapperWidth } else if (btnLeftStyle < 0) { btnLeftStyle = 0}至此,一個(gè)簡(jiǎn)單的移動(dòng)端滾動(dòng)條就實(shí)現(xiàn)了
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答