Простой слайдер на JavaScript
Доброго времени суток! Сегодня мы рассмотрим с Вами простой пример слайдера на JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Slider</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
.carousel-item {
height: 500px;
display: none;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.carousel-item.active {
display: flex;
}
.carousel {
position: relative;
overflow: hidden;
}
.carousel-control-prev, .carousel-control-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
border: none;
color: white;
padding: 10px;
cursor: pointer;
}
.carousel-control-prev {
left: 10px;
}
.carousel-control-next {
right: 10px;
}
</style>
</head>
<body>
<div class="container mt-5">
<div id="customCarousel" class="carousel">
<div class="carousel-item active">
<img src="https://via.placeholder.com/800x400" alt="Slide 1">
</div>
<div class="carousel-item">
<img src="https://via.placeholder.com/800x400" alt="Slide 2">
</div>
<div class="carousel-item">
<img src="https://via.placeholder.com/800x400" alt="Slide 3">
</div>
<button class="carousel-control-prev" onclick="prevSlide()">❮</button>
<button class="carousel-control-next" onclick="nextSlide()">❯</button>
</div>
</div>
<script>
let currentIndex = 0;
let direction = 1;
const slides = document.querySelectorAll('.carousel-item');
function showSlide(index) {
slides.forEach((slide, i) => {
slide.classList.toggle('active', i === index);
});
}
function nextSlide() {
if (currentIndex === slides.length - 1) {
direction = -1;
}
currentIndex = (currentIndex + direction + slides.length) % slides.length;
showSlide(currentIndex);
}
function prevSlide() {
if (currentIndex === 0) {
direction = 1;
}
currentIndex = (currentIndex + direction + slides.length) % slides.length;
showSlide(currentIndex);
}
setInterval(nextSlide, 3000);
</script>
</body>
</html>
-
- Михаил Русаков
Комментарии (0):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.