Many new events have been added to HTML, but due to compatibility issues, many events are not widely used. Next, we will introduce some useful mobile touch events: touchstart, touchmove, touchend.
introduceLet’s briefly introduce these events:
These touch events have common dom properties. In addition, they contain three properties for tracking touches:
Each touch object contains the following properties:
Now that you understand the characteristics of touch events, let’s start the exciting practical session.
Actual combatLet's use touch events to implement a sliding progress bar on the mobile side.
Let’s lay out the HTML first
<div class=progress-wrapper> <div class=progress></div> <div class=progress-btn></div></div>
CSS part omitted here
Get the dom element and initialize the touch starting point and the distance between the button and the leftmost part of the container
const progressWrapper = document.querySelector('.progress-wrapper')const progress = document.querySelector('.progress')const progressBtn = document.querySelector('.progress-btn')const progressWrapperWidth = progressWrapper.offsetWidthlet touchPoint = 0let btnLeft = 0Listen for touchstart event
progressBtn.addEventListener('touchstart', e => { let touch = e.touches[0] touchPoint = touch.clientX // Get the initial position of the touch btnLeft = parseInt(getComputedStyle(progressBtn, null)['left'], 10 ) // Ignore IE browser compatibility here})Listen for touchmove events
progressBtn.addEventListener('touchmove', e => {e.preventDefault() let touch = e.touches[0] let diffX = touch.clientX - touchPoint // Calculate the changed distance by the difference between the current position and the initial position let btnLeftStyle = btnLeft + diffX // Define a new left value for the button touch.target.style.left = btnLeftStyle + 'px' progress.style.width = (btnLeftStyle / progressWrapperWidth) * 100 + '%' // Calculate the length percentage of the progress bar through the ratio of the left value of the button to the length of the progress bar container})Through a series of logical operations, our progress bar has been basically implemented, but a problem has been discovered. When the touch position exceeds the progress bar container, a bug will occur. Let's make some restrictions.
if (btnLeftStyle > progressWrapperWidth) { btnLeftStyle = progressWrapperWidth } else if (btnLeftStyle < 0) { btnLeftStyle = 0}At this point, a simple mobile scroll bar has been implemented
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.