Anonymous
Я испытываю проблему со стрелой в моем коде; это не функционирует должным образом
Сообщение
Anonymous » 17 фев 2025, 07:30
Я разрабатываю карусель для своего веб -сайта, где пользователи могут перемещаться вперед и назад между картами, используя стрелки, а карты должны быть бесконечно зацикливаться. Тем не менее, нажатие на стрелки в настоящее время не влияет. Карта в карусели. Кроме того, карусель должна иметь функцию «бесконечного» петли, что означает, что достижение последней карты должно автоматически переходить обратно на первую карту. На данный момент события стрелки нажимают, что не функционируют, как и ожидалось. < /P>
html: < /p>
Код: Выделить всё
Carrossel de Produtos
Explore Nossas Linhas de Produtos
Descubra nossa coleção completa de móveis profissionais, projetados para
transformar seu ambiente de trabalho com estilo e funcionalidade.
[i][/i]
[i][/i]
< /code>
css: < /p>
.carousel-section {
background-color: #f8f9fa;
padding: 4rem 0;
}
.carousel-container {
position: relative;
padding: 0 60px; /* Espaço para os botões */
}
.carousel-wrapper {
overflow: hidden;
position: relative;
}
.carousel-track {
display: flex;
gap: 2rem;
transition: transform 0.5s ease-in-out;
cursor: grab;
}
.carousel-track.dragging {
cursor: grabbing;
transition: none;
}
/* Cards */
.carousel-card {
flex: 0 0 300px;
background: white;
border-radius: 1rem;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.carousel-card:hover {
transform: translateY(-10px);
}
.card-image {
height: 200px;
overflow: hidden;
}
.card-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.card-content {
padding: 1.5rem;
}
.card-title {
font-size: 1.25rem;
font-weight: bold;
margin-bottom: 0.5rem;
color: #333;
}
.card-category {
display: inline-block;
padding: 0.25rem 0.75rem;
background-color: #e9ecef;
color: #666;
border-radius: 1rem;
font-size: 0.875rem;
margin-bottom: 1rem;
}
.card-button {
display: inline-block;
padding: 0.5rem 1.5rem;
background-color: #0d6efd;
color: white;
border: none;
border-radius: 0.5rem;
cursor: pointer;
transition: background-color 0.3s;
text-decoration: none;
width: 100%;
text-align: center;
}
.card-button:hover {
background-color: #0b5ed7;
}
/* Botões de navegação */
.carousel-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
border-radius: 50%;
background: white;
border: none;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
cursor: pointer;
z-index: 10;
transition: all 0.3s ease;
}
.carousel-button:hover {
background: #f8f9fa;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.carousel-button.prev {
left: 0;
}
.carousel-button.next {
right: 0;
}
/* Responsividade */
@media (max-width: 768px) {
.carousel-card {
flex: 0 0 calc(100% - 2rem);
}
.carousel-container {
padding: 0 40px;
}
}
< /code>
javascript: < /p>
class Carousel {
constructor() {
// Elementos do DOM
this.container = document.querySelector('.carousel-wrapper');
this.track = document.querySelector('.carousel-track');
this.prevButton = document.querySelector('.carousel-button.prev');
this.nextButton = document.querySelector('.carousel-button.next');
// Estado do carrossel
this.isDragging = false;
this.startX = 0;
this.scrollLeft = 0;
// Dados dos produtos
this.products = [
{
id: 1,
title: 'Linha Escritório',
category: 'Escritório',
description: 'Móveis ergonômicos para seu ambiente de trabalho',
image: 'https://images.unsplash.com/photo-1524758631624-e2822e304c36?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80'
},
{
id: 2,
title: 'Linha Sala',
category: 'Sala',
description: 'Conforto e elegância para suas reuniões',
image: 'https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80'
},
{
id: 3,
title: 'Linha Armários',
category: 'Armários',
description: 'Organização e praticidade para seu espaço',
image: 'https://images.unsplash.com/photo-1595428774223-ef52624120d2?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80'
},
{
id: 4,
title: 'Linha Executiva',
category: 'Executivo',
description: 'Sofisticação para ambientes corporativos',
image: 'https://images.unsplash.com/photo-1497366216548-37526070297c?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80'
}
];
this.initialize();
}
initialize() {
this.renderCards();
this.addEventListeners();
}
renderCards() {
// Duplica os produtos para criar o efeito infinito
const items = [...this.products, ...this.products, ...this.products];
this.track.innerHTML = items.map(product => `
[img]${product.image}[/img]
${product.category}
${product.title}
${product.description}
[url=/produtos/${product.id}]Explorar[/url]
`).join('');
}
addEventListeners() {
// Navegação por botões
this.prevButton.addEventListener('click', () => this.scroll('left'));
this.nextButton.addEventListener('click', () => this.scroll('right'));
// Eventos de mouse para drag
this.track.addEventListener('mousedown', this.startDragging.bind(this));
this.track.addEventListener('mousemove', this.drag.bind(this));
this.track.addEventListener('mouseup', this.stopDragging.bind(this));
this.track.addEventListener('mouseleave', this.stopDragging.bind(this));
// Previne o menu de contexto ao arrastar
this.track.addEventListener('contextmenu', e => e.preventDefault());
}
startDragging(e) {
if (e.button !== 0) return; // Apenas botão esquerdo do mouse
this.isDragging = true;
this.track.classList.add('dragging');
this.startX = e.pageX - this.track.offsetLeft;
this.scrollLeft = this.track.scrollLeft;
}
drag(e) {
if (!this.isDragging) return;
e.preventDefault();
const x = e.pageX - this.track.offsetLeft;
const walk = (x - this.startX) * 2;
this.track.scrollLeft = this.scrollLeft - walk;
}
stopDragging() {
this.isDragging = false;
this.track.classList.remove('dragging');
}
scroll(direction) {
const cardWidth = this.track.querySelector('.carousel-card').offsetWidth + parseInt(window.getComputedStyle(this.track).gap); // Corrigido para garantir que o valor seja numérico
const scrollAmount = direction === 'left' ? -cardWidth : cardWidth;
this.track.scrollBy({
left: scrollAmount,
behavior: 'smooth'
});
}
}
// Inicializa o carrossel quando o DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
new Carousel();
});
Я надеюсь, что вы все сможете помочь мне в том, чтобы заставить стрелки функционировать должным образом.
Подробнее здесь:
https://stackoverflow.com/questions/794 ... ing-proper
1739766622
Anonymous
Я разрабатываю карусель для своего веб -сайта, где пользователи могут перемещаться вперед и назад между картами, используя стрелки, а карты должны быть бесконечно зацикливаться. Тем не менее, нажатие на стрелки в настоящее время не влияет. Карта в карусели. Кроме того, карусель должна иметь функцию «бесконечного» петли, что означает, что достижение последней карты должно автоматически переходить обратно на первую карту. На данный момент события стрелки нажимают, что не функционируют, как и ожидалось. < /P> html: < /p> [code] Carrossel de Produtos Explore Nossas Linhas de Produtos Descubra nossa coleção completa de móveis profissionais, projetados para transformar seu ambiente de trabalho com estilo e funcionalidade. [i][/i] [i][/i] < /code> css: < /p> .carousel-section { background-color: #f8f9fa; padding: 4rem 0; } .carousel-container { position: relative; padding: 0 60px; /* Espaço para os botões */ } .carousel-wrapper { overflow: hidden; position: relative; } .carousel-track { display: flex; gap: 2rem; transition: transform 0.5s ease-in-out; cursor: grab; } .carousel-track.dragging { cursor: grabbing; transition: none; } /* Cards */ .carousel-card { flex: 0 0 300px; background: white; border-radius: 1rem; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease; } .carousel-card:hover { transform: translateY(-10px); } .card-image { height: 200px; overflow: hidden; } .card-image img { width: 100%; height: 100%; object-fit: cover; } .card-content { padding: 1.5rem; } .card-title { font-size: 1.25rem; font-weight: bold; margin-bottom: 0.5rem; color: #333; } .card-category { display: inline-block; padding: 0.25rem 0.75rem; background-color: #e9ecef; color: #666; border-radius: 1rem; font-size: 0.875rem; margin-bottom: 1rem; } .card-button { display: inline-block; padding: 0.5rem 1.5rem; background-color: #0d6efd; color: white; border: none; border-radius: 0.5rem; cursor: pointer; transition: background-color 0.3s; text-decoration: none; width: 100%; text-align: center; } .card-button:hover { background-color: #0b5ed7; } /* Botões de navegação */ .carousel-button { position: absolute; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border-radius: 50%; background: white; border: none; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); cursor: pointer; z-index: 10; transition: all 0.3s ease; } .carousel-button:hover { background: #f8f9fa; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } .carousel-button.prev { left: 0; } .carousel-button.next { right: 0; } /* Responsividade */ @media (max-width: 768px) { .carousel-card { flex: 0 0 calc(100% - 2rem); } .carousel-container { padding: 0 40px; } } < /code> javascript: < /p> class Carousel { constructor() { // Elementos do DOM this.container = document.querySelector('.carousel-wrapper'); this.track = document.querySelector('.carousel-track'); this.prevButton = document.querySelector('.carousel-button.prev'); this.nextButton = document.querySelector('.carousel-button.next'); // Estado do carrossel this.isDragging = false; this.startX = 0; this.scrollLeft = 0; // Dados dos produtos this.products = [ { id: 1, title: 'Linha Escritório', category: 'Escritório', description: 'Móveis ergonômicos para seu ambiente de trabalho', image: 'https://images.unsplash.com/photo-1524758631624-e2822e304c36?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80' }, { id: 2, title: 'Linha Sala', category: 'Sala', description: 'Conforto e elegância para suas reuniões', image: 'https://images.unsplash.com/photo-1555041469-a586c61ea9bc?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80' }, { id: 3, title: 'Linha Armários', category: 'Armários', description: 'Organização e praticidade para seu espaço', image: 'https://images.unsplash.com/photo-1595428774223-ef52624120d2?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80' }, { id: 4, title: 'Linha Executiva', category: 'Executivo', description: 'Sofisticação para ambientes corporativos', image: 'https://images.unsplash.com/photo-1497366216548-37526070297c?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80' } ]; this.initialize(); } initialize() { this.renderCards(); this.addEventListeners(); } renderCards() { // Duplica os produtos para criar o efeito infinito const items = [...this.products, ...this.products, ...this.products]; this.track.innerHTML = items.map(product => ` [img]${product.image}[/img] ${product.category} ${product.title} ${product.description} [url=/produtos/${product.id}]Explorar[/url] `).join(''); } addEventListeners() { // Navegação por botões this.prevButton.addEventListener('click', () => this.scroll('left')); this.nextButton.addEventListener('click', () => this.scroll('right')); // Eventos de mouse para drag this.track.addEventListener('mousedown', this.startDragging.bind(this)); this.track.addEventListener('mousemove', this.drag.bind(this)); this.track.addEventListener('mouseup', this.stopDragging.bind(this)); this.track.addEventListener('mouseleave', this.stopDragging.bind(this)); // Previne o menu de contexto ao arrastar this.track.addEventListener('contextmenu', e => e.preventDefault()); } startDragging(e) { if (e.button !== 0) return; // Apenas botão esquerdo do mouse this.isDragging = true; this.track.classList.add('dragging'); this.startX = e.pageX - this.track.offsetLeft; this.scrollLeft = this.track.scrollLeft; } drag(e) { if (!this.isDragging) return; e.preventDefault(); const x = e.pageX - this.track.offsetLeft; const walk = (x - this.startX) * 2; this.track.scrollLeft = this.scrollLeft - walk; } stopDragging() { this.isDragging = false; this.track.classList.remove('dragging'); } scroll(direction) { const cardWidth = this.track.querySelector('.carousel-card').offsetWidth + parseInt(window.getComputedStyle(this.track).gap); // Corrigido para garantir que o valor seja numérico const scrollAmount = direction === 'left' ? -cardWidth : cardWidth; this.track.scrollBy({ left: scrollAmount, behavior: 'smooth' }); } } // Inicializa o carrossel quando o DOM estiver pronto document.addEventListener('DOMContentLoaded', () => { new Carousel(); }); [/code] Я надеюсь, что вы все сможете помочь мне в том, чтобы заставить стрелки функционировать должным образом. Подробнее здесь: [url]https://stackoverflow.com/questions/79444404/im-experiencing-an-issue-with-the-arrow-in-my-code-its-not-functioning-proper[/url]