|
|
|
let currentIndex = 0; |
|
|
|
|
|
let startTouchPosition = 0; |
|
let endTouchPosition = 0; |
|
|
|
const slider = document.querySelector('.slider'); |
|
const totalSlides = slider.children.length; |
|
|
|
|
|
function moveToSlide(n) { |
|
let newSlidePosition = ((n - 1) * -100) / totalSlides; |
|
slider.style.transform = `translateX(${newSlidePosition}%)`; |
|
currentIndex = n; |
|
} |
|
|
|
|
|
document.addEventListener('DOMContentLoaded', () => { |
|
moveToSlide(currentIndex); |
|
}); |
|
|
|
|
|
|
|
document.addEventListener('keydown', (e) => { |
|
if (e.key === 'ArrowLeft') { |
|
|
|
if (currentIndex > 0) { |
|
|
|
moveToSlide(currentIndex - 1); |
|
} |
|
} else if (e.key === 'ArrowRight') { |
|
|
|
if (currentIndex < totalSlides - 1) { |
|
|
|
moveToSlide(currentIndex + 1); |
|
} |
|
} |
|
}); |
|
|
|
|
|
slider.addEventListener('touchstart', (e) => { |
|
startTouchPosition = e.touches[0].clientX; |
|
}); |
|
|
|
|
|
slider.addEventListener('touchend', (e) => { |
|
endTouchPosition = e.changedTouches[0].clientX; |
|
handleTouchMove(); |
|
}); |
|
|
|
function handleTouchMove() { |
|
if (startTouchPosition - endTouchPosition > 50 && currentIndex < totalSlides - 1) { |
|
|
|
moveToSlide(currentIndex + 1); |
|
} else if (endTouchPosition - startTouchPosition > 50 && currentIndex > 0) { |
|
|
|
moveToSlide(currentIndex - 1); |
|
} |
|
} |
|
|
|
|
|
|
|
slider.addEventListener('wheel', (e) => { |
|
e.preventDefault(); |
|
|
|
if (e.deltaY < 0 && currentIndex > 0) { |
|
|
|
moveToSlide(currentIndex - 1); |
|
} else if (e.deltaY > 0 && currentIndex < totalSlides - 1) { |
|
|
|
moveToSlide(currentIndex + 1); |
|
} |
|
}); |
|
|
|
|