/
nikitaremyga
/
FreakTeam
Обзор
Документация
Войти
/
nikitaremyga
/
FreakTeam
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
main_script.js
230 строк
10 KB
Nikita
2 commit
11 июн 2025, 23:35
11 июн 2025, 23:35
4d11b51
Код
Авторство
О чём код?
document.addEventListener('DOMContentLoaded', function() { // Массив изображений для карусели (можно заменить на свои) const images = [ { url: 'about_pic.jpg', }, { url: 'https://source.unsplash.com/random/800x400?nature,2', title: 'Природа 2' }, { url: 'https://source.unsplash.com/random/800x400?nature,3', title: 'Природа 3' }, { url: 'https://source.unsplash.com/random/800x400?nature,4', title: 'Природа 4' }, { url: 'https://source.unsplash.com/random/800x400?nature,5', title: 'Природа 5' } ]; const carousel = document.querySelector('.carousel'); const prevBtn = document.querySelector('.prev-btn'); const nextBtn = document.querySelector('.next-btn'); const indicatorsContainer = document.querySelector('.carousel-indicators'); let currentIndex = 0; let intervalId; const slideInterval = 3000; // Интервал автоматической смены слайдов (3 секунды) // Создаем элементы карусели function createCarouselItems() { carousel.innerHTML = ''; indicatorsContainer.innerHTML = ''; images.forEach((image, index) => { // Создаем элемент слайда const item = document.createElement('div'); item.className = 'carousel-item'; const img = document.createElement('img'); img.src = image.url; img.alt = image.title; const caption = document.createElement('div'); caption.className = 'carousel-caption'; caption.textContent = image.title; item.appendChild(img); item.appendChild(caption); carousel.appendChild(item); // Создаем индикаторы const indicator = document.createElement('div'); indicator.className = 'indicator'; if (index === 0) indicator.classList.add('active'); indicator.addEventListener('click', () => goToSlide(index)); indicatorsContainer.appendChild(indicator); }); // Клонируем первый и последний слайды для бесконечного эффекта const firstClone = carousel.children[0].cloneNode(true); const lastClone = carousel.children[images.length - 1].cloneNode(true); firstClone.id = 'first-clone'; lastClone.id = 'last-clone'; carousel.prepend(lastClone); carousel.appendChild(firstClone); // Устанавливаем начальную позицию carousel.style.transform = `translateX(-${100}%)`; } // Переход к конкретному слайду function goToSlide(index) { currentIndex = index; updateCarousel(); } // Обновление карусели function updateCarousel() { carousel.style.transition = 'transform 0.5s ease-in-out'; carousel.style.transform = `translateX(-${(currentIndex + 1) * 100}%)`; // Обновляем активный индикатор const indicators = document.querySelectorAll('.indicator'); indicators.forEach((indicator, i) => { if (i === currentIndex) { indicator.classList.add('active'); } else { indicator.classList.remove('active'); } }); } // Переход к следующему слайду function nextSlide() { if (currentIndex >= images.length - 1) { // Если это последний слайд, переходим к клону первого слайда currentIndex = 0; carousel.style.transition = 'none'; carousel.style.transform = `translateX(-${(images.length + 1) * 100}%)`; // Принудительное обновление DOM setTimeout(() => { carousel.style.transition = 'transform 0.5s ease-in-out'; updateCarousel(); }, 0); } else { currentIndex++; updateCarousel(); } } // Переход к предыдущему слайду function prevSlide() { if (currentIndex <= 0) { // Если это первый слайд, переходим к клону последнего слайда currentIndex = images.length - 1; carousel.style.transition = 'none'; carousel.style.transform = `translateX(0%)`; // Принудительное обновление DOM setTimeout(() => { carousel.style.transition = 'transform 0.5s ease-in-out'; updateCarousel(); }, 0); } else { currentIndex--; updateCarousel(); } } // Обработчики событий для кнопок nextBtn.addEventListener('click', () => { nextSlide(); resetInterval(); }); prevBtn.addEventListener('click', () => { prevSlide(); resetInterval(); }); // Обработчик события завершения перехода carousel.addEventListener('transitionend', () => { // Если мы на клоне первого слайда (после последнего настоящего) if (currentIndex === 0 && carousel.style.transform.includes(`-${(images.length + 1) * 100}%`)) { carousel.style.transition = 'none'; carousel.style.transform = `translateX(-${100}%)`; setTimeout(() => { carousel.style.transition = 'transform 0.5s ease-in-out'; }, 0); } // Если мы на клоне последнего слайда (перед первым настоящим) if (currentIndex === images.length - 1 && carousel.style.transform.includes('0%')) { carousel.style.transition = 'none'; carousel.style.transform = `translateX(-${images.length * 100}%)`; setTimeout(() => { carousel.style.transition = 'transform 0.5s ease-in-out'; }, 0); } }); // Автоматическая смена слайдов function startInterval() { intervalId = setInterval(nextSlide, slideInterval); } function resetInterval() { clearInterval(intervalId); startInterval(); } // Инициализация карусели createCarouselItems(); startInterval(); // Остановка автоматической смены при наведении carousel.addEventListener('mouseenter', () => { clearInterval(intervalId); }); carousel.addEventListener('mouseleave', () => { startInterval(); }); // Поддержка свайпов на мобильных устройствах let touchStartX = 0; let touchEndX = 0; carousel.addEventListener('touchstart', (e) => { touchStartX = e.changedTouches[0].screenX; clearInterval(intervalId); }, {passive: true}); carousel.addEventListener('touchend', (e) => { touchEndX = e.changedTouches[0].screenX; handleSwipe(); startInterval(); }, {passive: true}); function handleSwipe() { const threshold = 50; if (touchEndX < touchStartX - threshold) { nextSlide(); } else if (touchEndX > touchStartX + threshold) { prevSlide(); } } }); const burger = document.getElementById("burger_icon"); const menu = document.getElementById("menu_content"); burger.addEventListener("click", () => { menu.classList.toggle("mobile-shown"); }); // Для клавиатурной навигации по бургеру (Enter и пробел) burger.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); menu.classList.toggle("mobile-shown"); } });