author: 专注前端开发,分享JavaScript干货
title: JavaScript实战②|电商网站交互效果,轮播图与购物车
update: 2026-04-28
tags: JavaScript,实战项目,电商网站,轮播图,购物车,DOM操作
作者:专注前端开发,分享JavaScript干货
更新时间:2026年4月
适合人群:掌握JS基础,想学习电商交互效果的开发者
前言:电商网站有哪些交互?
电商网站常见的交互效果:
- 轮播图(Banner Slider)
- 商品添加到购物车
- 购物车数量更新
- 商品筛选与排序
这些效果都是前端开发的核心技能。
一、轮播图实现
1.1 HTML 结构
html
<div class="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="banner1.jpg" alt="Banner 1">
</div>
<div class="carousel-item">
<img src="banner2.jpg" alt="Banner 2">
</div>
<div class="carousel-item">
<img src="banner3.jpg" alt="Banner 3">
</div>
</div>
<!-- 左右箭头 -->
<button class="carousel-control prev">❮</button>
<button class="carousel-control next">❯</button>
<!-- 指示器 -->
<div class="carousel-indicators">
<span class="indicator active" data-slide="0"></span>
<span class="indicator" data-slide="1"></span>
<span class="indicator" data-slide="2"></span>
</div>
</div>
1.2 CSS 样式
css
.carousel {
position: relative;
width: 100%;
max-width: 1200px;
margin: 0 auto;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease;
}
.carousel-item {
min-width: 100%;
flex-shrink: 0;
}
.carousel-item img {
width: 100%;
height: 400px;
object-fit: cover;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0,0,0,0.5);
color: white;
border: none;
padding: 15px 20px;
cursor: pointer;
font-size: 20px;
}
.carousel-control.prev { left: 10px; }
.carousel-control.next { right: 10px; }
.carousel-indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 10px;
}
.indicator {
width: 12px;
height: 12px;
border-radius: 50%;
background: rgba(255,255,255,0.5);
cursor: pointer;
}
.indicator.active {
background: white;
}
1.3 JavaScript 实现
javascript
class Carousel {
constructor(element) {
this.carousel = element;
this.inner = element.querySelector('.carousel-inner');
this.items = element.querySelectorAll('.carousel-item');
this.prevBtn = element.querySelector('.carousel-control.prev');
this.nextBtn = element.querySelector('.carousel-control.next');
this.indicators = element.querySelectorAll('.indicator');
this.currentIndex = 0;
this.totalSlides = this.items.length;
this.autoPlayInterval = null;
this.init();
}
init() {
this.bindEvents();
this.startAutoPlay();
}
bindEvents() {
this.prevBtn.addEventListener('click', () => {
this.prev();
this.resetAutoPlay();
});
this.nextBtn.addEventListener('click', () => {
this.next();
this.resetAutoPlay();
});
this.indicators.forEach((indicator, index) => {
indicator.addEventListener('click', () => {
this.goTo(index);
this.resetAutoPlay();
});
});
// 鼠标悬停暂停
this.carousel.addEventListener('mouseenter', () => this.stopAutoPlay());
this.carousel.addEventListener('mouseleave', () => this.startAutoPlay());
}
goTo(index) {
this.currentIndex = index;
this.updateCarousel();
}
next() {
this.currentIndex = (this.currentIndex + 1) % this.totalSlides;
this.updateCarousel();
}
prev() {
this.currentIndex = (this.currentIndex - 1 + this.totalSlides) % this.totalSlides;
this.updateCarousel();
}
updateCarousel() {
// 移动轮播图
this.inner.style.transform = `translateX(-${this.currentIndex * 100}%)`;
// 更新指示器
this.indicators.forEach((indicator, index) => {
indicator.classList.toggle('active', index === this.currentIndex);
});
}
startAutoPlay() {
this.autoPlayInterval = setInterval(() => this.next(), 3000);
}
stopAutoPlay() {
clearInterval(this.autoPlayInterval);
}
resetAutoPlay() {
this.stopAutoPlay();
this.startAutoPlay();
}
}
// 初始化轮播图
const carousel = new Carousel(document.querySelector('.carousel'));
二、购物车功能
2.1 商品列表 HTML
html
<div class="products">
<div class="product-card" data-id="1" data-name="iPhone 15" data-price="5999">
<img src="iphone.jpg" alt="iPhone">
<h3>iPhone 15</h3>
<p class="price">¥5999</p>
<button class="add-to-cart">加入购物车</button>
</div>
<div class="product-card" data-id="2" data-name="MacBook Pro" data-price="14999">
<img src="macbook.jpg" alt="MacBook">
<h3>MacBook Pro</h3>
<p class="price">¥14999</p>
<button class="add-to-cart">加入购物车</button>
</div>
</div>
<!-- 购物车图标 -->
<div class="cart-icon">
🛒 <span class="cart-count">0</span>
</div>
2.2 购物车 JavaScript
javascript
class ShoppingCart {
constructor() {
this.cart = JSON.parse(localStorage.getItem('cart')) || [];
this.cartCount = document.querySelector('.cart-count');
this.init();
}
init() {
this.bindEvents();
this.updateCartUI();
}
bindEvents() {
document.querySelectorAll('.add-to-cart').forEach(btn => {
btn.addEventListener('click', (e) => {
const card = e.target.closest('.product-card');
const product = {
id: parseInt(card.dataset.id),
name: card.dataset.name,
price: parseFloat(card.dataset.price),
quantity: 1
};
this.addToCart(product);
});
});
}
addToCart(product) {
const existingItem = this.cart.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity++;
} else {
this.cart.push(product);
}
this.saveCart();
this.updateCartUI();
this.showNotification(`${product.name} 已加入购物车`);
}
removeFromCart(productId) {
this.cart = this.cart.filter(item => item.id !== productId);
this.saveCart();
this.updateCartUI();
}
updateQuantity(productId, quantity) {
const item = this.cart.find(item => item.id === productId);
if (item) {
item.quantity = Math.max(0, quantity);
if (item.quantity === 0) {
this.removeFromCart(productId);
} else {
this.saveCart();
this.updateCartUI();
}
}
}
getTotalCount() {
return this.cart.reduce((sum, item) => sum + item.quantity, 0);
}
getTotalPrice() {
return this.cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
saveCart() {
localStorage.setItem('cart', JSON.stringify(this.cart));
}
updateCartUI() {
this.cartCount.textContent = this.getTotalCount();
}
showNotification(message) {
// 创建通知元素
const notification = document.createElement('div');
notification.className = 'notification';
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 15px 25px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1000;
animation: slideIn 0.3s ease;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 2000);
}
}
// 初始化购物车
const cart = new ShoppingCart();
三、知识点回顾
| 知识点 | 应用 |
|---|---|
| Class | 封装轮播图和购物车逻辑 |
| DOM 操作 | 更新轮播图位置、购物车数量 |
| 事件委托 | 商品添加按钮的事件处理 |
| LocalStorage | 购物车数据持久化 |
| 定时器 | 轮播图自动播放 |
| CSS Transform | 轮播图滑动动画 |
四、课后作业
- 给轮播图添加触摸滑动支持(移动端)
- 实现购物车详情弹窗,可以修改数量
- 添加商品收藏功能( hearts 图标)
有问题欢迎评论区留言,大家一起讨论!
标签:JavaScript | 实战项目 | 电商网站 | 轮播图 | 购物车 | DOM操作