Hier ist ein einfaches Beispiel in Vanilla Javascript.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Carousel mit Drehfunktion</title>
<style>
.carousel-container {
width: 300px;
overflow: hidden;
position: relative;
}
.carousel-track {
display: flex;
transition: transform 0.3s ease;
cursor: grab;
}
.carousel-item {
min-width: 100%;
}
img {
max-width: 100%;
height: auto;
}
.carousel-controls {
display: flex;
justify-content: space-between;
margin-top: 10px;
}
.carousel-arrow {
min-width: 200px;
background: green;
text-align: center;
cursor: pointer;
padding: 5px;
}
</style>
</head>
<body>
<div class="carousel-container">
<div class="carousel-track" id="carouselTrack">
<div class="carousel-item"><img src="1.jpg" alt="Bild 1"></div>
<div class="carousel-item"><img src="2.jpg" alt="Bild 2"></div>
<div class="carousel-item"><img src="3.jpg" alt="Bild 3"></div>
</div>
</div>
<div class="carousel-controls">
<div class="carousel-arrow" id="next"><<</div>
<div class="carousel-arrow" id="prev">>></div>
</div>
<script>
const carouselTrack = document.getElementById('carouselTrack');
let isDragging = false;
let startPosition = 0;
let currentTranslate = 0;
let prevTranslate = 0;
const prevButton = document.getElementById('prev');
const nextButton = document.getElementById('next');
prevButton.addEventListener('click', () => moveCarousel(-1));
nextButton.addEventListener('click', () => moveCarousel(1));
carouselTrack.addEventListener('mousedown', (e) => {
isDragging = true;
startPosition = e.clientX;
prevTranslate = currentTranslate;
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
});
function handleMouseMove(e) {
if (isDragging) {
const currentPosition = e.clientX;
currentTranslate = prevTranslate + currentPosition - startPosition;
updateCarouselPosition();
}
}
function handleMouseUp() {
isDragging = false;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
}
function updateCarouselPosition() {
carouselTrack.style.transform = `translateX(${currentTranslate}px)`;
}
function moveCarousel(direction) {
const itemWidth = carouselTrack.querySelector('.carousel-item').offsetWidth;
currentTranslate += direction * itemWidth;
updateCarouselPosition();
}
</script>
</body>
</html>