HTML5觸控事件實現移動端簡易進度條

該使用者已成仙發表於2018-05-01

前言

HTML中新新增了許多新的事件,但由於相容性的問題,許多事件都沒有廣泛的應用,接下來為大家介紹一些好用的移動端觸控事件: touchstart、touchmove、touchend。

介紹

下面我們來簡單介紹一下這幾個事件:

  • touchstart: 當手指觸控螢幕時候觸發,即使已經有一個手指放在螢幕上也會觸發。
  • touchmove:當手指在螢幕上滑動的時候連續地觸發。在這個事件發生期間,呼叫preventDefault()事件可以阻止滾動。
  • touchend:當手指從螢幕上離開的時候觸發。

這些觸控事件具有常見的dom屬性。此外,他們還包含著三個用於跟蹤觸控的屬性:

  • touches:表示當前跟蹤的觸控操作的touch物件的陣列。
  • targetTouches:特定於事件目標的Touch物件的陣列。
  • changeTouches:表示自上次觸控以來發生了什麼改變的Touch物件的陣列。

每個touch物件包含的屬性如下:

  • clientX:觸控目標在視口中的x座標。
  • clientY:觸控目標在視口中的y座標。
  • pageX:觸控目標在頁面中的x座標。
  • pageY:觸控目標在頁面中的y座標。
  • screenX:screenX:觸控目標在螢幕中的x座標。
  • screenY:screenX:觸控目標在螢幕中的x座標。
  • identifier:標識觸控的唯一ID。
  • target:screenX:觸控目標在螢幕中的x座標。

瞭解了觸控事件的特徵,那就開始緊張刺激的實戰環節吧

實戰

下面我們來通過使用觸控事件來實現一個移動端可滑動的進度條

我們先進行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
複製程式碼

監聽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
}
複製程式碼

至此,一個簡單的移動端滾動條就實現了

相關文章