HTML에는 새로운 이벤트가 많이 추가되었지만 호환성 문제로 인해 널리 사용되지 않는 이벤트가 많습니다. 다음으로 유용한 모바일 터치 이벤트인 touchstart, touchmove, touchend를 소개하겠습니다.
소개하다해당 이벤트를 간략하게 소개하자면 다음과 같습니다.
이러한 터치 이벤트에는 공통 DOM 속성이 있습니다. 또한 터치 추적을 위한 세 가지 속성이 포함되어 있습니다.
각 터치 개체에는 다음 속성이 포함되어 있습니다.
이제 터치 이벤트의 특성을 이해했으므로 흥미로운 실습 세션을 시작하겠습니다.
실제 전투터치 이벤트를 사용하여 모바일 측에서 슬라이딩 진행률 표시줄을 구현해 보겠습니다.
먼저 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터치스타트 이벤트 듣기
ProgressBtn.addEventListener('touchstart', e => { let touch = e.touches[0] touchPoint = touch.clientX // 터치의 초기 위치를 가져옵니다. btnLeft =parseInt(getCompulatedStyle(progressBtn, null)['left'] , 10 ) // 여기서는 IE 브라우저 호환성을 무시합니다.})touchmove 이벤트 듣기
ProgressBtn.addEventListener('touchmove', e => {e.preventDefault() let touch = e.touches[0] let diffX = touch.clientX - touchPoint // 현재 위치와 초기 위치의 차이로 변경된 거리를 계산합니다. position let btnLeftStyle = btnLeft + diffX // 버튼의 새 왼쪽 값 정의 touch.target.style.left = btnLeftStyle + 'px' Progress.style.width = (btnLeftStyle / ProgressWrapperWidth) * 100 + '%' // 진행률 표시줄 컨테이너의 길이에 대한 버튼의 왼쪽 값의 비율을 통해 진행률 표시줄의 길이 백분율을 계산합니다.})일련의 논리 연산을 통해 기본적으로 진행률 표시줄이 구현되었지만 터치 위치가 진행률 표시줄 컨테이너를 초과하면 몇 가지 제한 사항이 발생합니다.
if (btnLeftStyle > ProgressWrapperWidth) { btnLeftStyle = ProgressWrapperWidth } else if (btnLeftStyle < 0) { btnLeftStyle = 0}이 시점에서 간단한 모바일 스크롤바가 구현되었습니다.
위의 내용은 이 기사의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 VeVb Wulin Network를 지지해 주시길 바랍니다.