-
evento touchstart: se activa cuando un dedo toca la pantalla, incluso si ya hay un dedo en la pantalla.
-
evento touchmove: Se activa continuamente cuando el dedo se desliza en la pantalla. Llamar al evento preventDefault() evita el desplazamiento durante este evento.
-
evento touchend: se activa cuando el dedo sale de la pantalla.
Diseño adaptativo del primer set rem
// 1rem = 10px
document.documentElement.style.fontSize =
document.documentElement.clientWidth / 37.5 + "px";
código HTML
<div id="app">
<divclass="wrap">
<div class="wrap-slider">
<div class="slider-item">page-1</div>
<div class="slider-item">page-2</div>
<div class="slider-item">page-3</div>
<div class="slider-item">page-4</div>
<div class="slider-item">page-5</div>
</div>
</div>
</div>
codigo css
body {
margin: 0;
}
html,
body,
#app {
height: 100%;
}
.wrap {
position: relative;
height: 100%;
overflow: hidden;
}
.wrap-slider {
display: flex;
position: absolute;
flex-direction: row;
width: 187.5rem;
height: 100%;
}
.slider-item {
display: flex;
justify-content: center;
align-items: center;
font-size: 5rem;
flex: 1;
}
.slider-item:nth-child(1) {
background-color: aqua;
}
.slider-item:nth-child(2) {
background-color: red;
}
.slider-item:nth-child(3) {
background-color: yellow;
}
.slider-item:nth-child(4) {
background-color: blue;
}
.slider-item:nth-child(5) {
background-color: rgb(132, 126, 126);
}
codigo js
const wrap = document.querySelector(".wrap");
const wrapSlider = document.querySelector(".wrap-slider");
const sliderItem = document.querySelectorAll(".slider-item");
const pageWidth = wrap.offsetWidth;
console.log(pageWidth, "pageWidth");
let startX = 0;
let moveX = 0;
let distanceX = 0;
let slidePageIndex = 0;
let isMove = false;
const init = () => {
bindEvent();
};
function bindEvent() {
wrapSlider.addEventListener("touchstart", handleTouchStart);
wrapSlider.addEventListener("touchmove", handleTouchMove);
wrapSlider.addEventListener("touchend", handleTouchEnd);
}
function handleTouchStart(e) {
startX = e.touches[0].clientX;
console.log(startX);
}
function handleTouchMove(e) {
moveX = e.touches[0].clientX;
distanceX = moveX - startX;
if (
(slidePageIndex === 0 && distanceX > 0) ||
(slidePageIndex === sliderItem.length - 1 && distanceX < 0)
)
return;
console.log(distanceX);
isMove = true;
setTranslateX(-slidePageIndex * pageWidth + distanceX);
}
function handleTouchEnd(e) {
if (isMove) {
if (Math.abs(distanceX) >= pageWidth / 3) {
if (distanceX > 0) {
slidePageIndex--;
}
if (distanceX < 0) {
slidePageIndex++;
}
}
setTranslateX(-slidePageIndex * pageWidth);
}
startX = 0;
moveX = 0;
distanceX = 0;
isMove = false;
}
function setTranslateX(transX) {
wrapSlider.style.transition = "all 0.1s";
wrapSlider.style.transform = `translateX(${
transX}px)`;
}
init();