dev / script.js
Aleksmorshen's picture
Update script.js
d4acec1 verified
// Плавный скролл
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const section = document.querySelector(this.getAttribute('href'));
section.scrollIntoView({ behavior: 'smooth' });
});
});
// Анимация при скролле
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
}, { threshold: 0.2 });
document.querySelectorAll('.service-card').forEach(element => {
observer.observe(element);
});
// Изменение шапки при скролле
window.addEventListener('scroll', () => {
const header = document.querySelector('.header');
if (window.scrollY > 50) {
header.classList.add('scrolled');
} else {
header.classList.remove('scrolled');
}
});
// Three.js 3D-анимация (плавающие сферы с контролем з-индекса)
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('three-canvas').appendChild(renderer.domElement);
// Свет
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xff6200, 1.2, 100);
pointLight.position.set(15, 15, 15);
scene.add(pointLight);
// Создание сфер
const spheres = [];
const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMaterial = new THREE.MeshPhongMaterial({ color: 0xff6200, emissive: 0xff6200, emissiveIntensity: 0.6, transparent: true, opacity: 0.8 });
for (let i = 0; i < 15; i++) {
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(
(Math.random() - 0.5) * 15,
(Math.random() - 0.5) * 15 - 5,
(Math.random() - 0.5) * 15
);
sphere.userData = { velocity: new THREE.Vector3((Math.random() - 0.5) * 0.015, (Math.random() - 0.5) * 0.015, (Math.random() - 0.5) * 0.015) };
scene.add(sphere);
spheres.push(sphere);
}
camera.position.z = 12;
camera.position.y = 2;
// Анимация сфер с ограничением
function animate() {
requestAnimationFrame(animate);
spheres.forEach(sphere => {
sphere.position.add(sphere.userData.velocity);
if (Math.abs(sphere.position.x) > 10) sphere.userData.velocity.x *= -0.9;
if (sphere.position.y > 5 || sphere.position.y < -10) sphere.userData.velocity.y *= -0.9;
if (Math.abs(sphere.position.z) > 10) sphere.userData.velocity.z *= -0.9;
sphere.rotation.x += 0.02;
sphere.rotation.y += 0.02;
});
renderer.render(scene, camera);
}
animate();
// Адаптация канваса
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Корзина с Local Storage
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function updateCart() {
// Сохраняем корзину в Local Storage
localStorage.setItem('cart', JSON.stringify(cart));
// Обновляем счетчик корзины
const cartCount = document.getElementById('cartCount');
if (cartCount) {
cartCount.textContent = cart.length;
}
// Обновляем содержимое модального окна
const cartItems = document.getElementById('cartItems');
if (cartItems) {
cartItems.innerHTML = '';
if (cart.length === 0) {
cartItems.innerHTML = '<li>Корзина пуста</li>';
} else {
cart.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
cartItems.appendChild(li);
});
}
}
}
// Функция для привязки событий
function initializeCart() {
// Привязываем события к кнопкам "Добавить в корзину"
const addToCartButtons = document.querySelectorAll('.add-to-cart-btn');
addToCartButtons.forEach(button => {
button.addEventListener('click', (e) => {
e.preventDefault(); // Предотвращаем стандартное поведение
e.stopPropagation(); // Останавливаем всплытие события до карточки
console.log('Кнопка "Добавить в корзину" нажата'); // Отладка
const serviceCard = button.closest('.service-card');
const serviceName = serviceCard.getAttribute('data-service');
console.log('Услуга:', serviceName); // Отладка
if (serviceName && !cart.includes(serviceName)) {
cart.push(serviceName);
updateCart();
alert(`${serviceName} добавлено в корзину!`);
} else if (cart.includes(serviceName)) {
alert(`${serviceName} уже в корзине!`);
} else {
console.error('Не удалось определить услугу для добавления в корзину');
}
});
});
// Убедимся, что карточка не перехватывает клик
const serviceCards = document.querySelectorAll('.service-card');
serviceCards.forEach(card => {
card.addEventListener('click', (e) => {
console.log('Клик по карточке (должно игнорироваться)'); // Отладка
});
});
// Открытие/закрытие модального окна корзины
const cartIcon = document.getElementById('cartIcon');
const cartModal = document.getElementById('cartModal');
const closeModal = document.getElementById('closeModal');
if (cartIcon && cartModal && closeModal) {
cartIcon.addEventListener('click', () => {
cartModal.style.display = 'flex';
updateCart();
});
closeModal.addEventListener('click', () => {
cartModal.style.display = 'none';
});
}
// Очистка корзины
const clearCartBtn = document.getElementById('clearCartBtn');
if (clearCartBtn) {
clearCartBtn.addEventListener('click', () => {
cart = [];
updateCart();
alert('Корзина очищена!');
});
}
// Рассчитать стоимость
const calculateBtn = document.getElementById('calculateBtn');
if (calculateBtn) {
calculateBtn.addEventListener('click', () => {
if (cart.length > 0) {
const message = `Здравствуйте! Интересуют следующие услуги: ${cart.join(', ')}. Прошу рассчитать стоимость.`;
const whatsappUrl = `https://wa.me/996500398754?text=${encodeURIComponent(message)}`;
window.open(whatsappUrl, '_blank');
cartModal.style.display = 'none';
cart = []; // Очищаем корзину после отправки
updateCart();
} else {
alert('Пожалуйста, выберите хотя бы одну услугу!');
}
});
}
}
// Инициализация корзины после загрузки DOM
document.addEventListener('DOMContentLoaded', () => {
initializeCart();
updateCart();
});