JavaScript实战②|电商网站交互效果,轮播图与购物车
author: 专注前端开发分享JavaScript干货title: JavaScript实战②电商网站交互效果轮播图与购物车update: 2026-04-28tags: JavaScript,实战项目,电商网站,轮播图,购物车,DOM操作作者专注前端开发分享JavaScript干货更新时间2026年4月适合人群掌握JS基础想学习电商交互效果的开发者前言电商网站有哪些交互电商网站常见的交互效果轮播图Banner Slider商品添加到购物车购物车数量更新商品筛选与排序这些效果都是前端开发的核心技能。一、轮播图实现1.1 HTML 结构divclasscarouseldivclasscarousel-innerdivclasscarousel-item activeimgsrcbanner1.jpgaltBanner 1/divdivclasscarousel-itemimgsrcbanner2.jpgaltBanner 2/divdivclasscarousel-itemimgsrcbanner3.jpgaltBanner 3/div/div!-- 左右箭头 --buttonclasscarousel-control prev❮/buttonbuttonclasscarousel-control next❯/button!-- 指示器 --divclasscarousel-indicatorsspanclassindicator activedata-slide0/spanspanclassindicatordata-slide1/spanspanclassindicatordata-slide2/span/div/div1.2 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 实现classCarousel{constructor(element){this.carouselelement;this.innerelement.querySelector(.carousel-inner);this.itemselement.querySelectorAll(.carousel-item);this.prevBtnelement.querySelector(.carousel-control.prev);this.nextBtnelement.querySelector(.carousel-control.next);this.indicatorselement.querySelectorAll(.indicator);this.currentIndex0;this.totalSlidesthis.items.length;this.autoPlayIntervalnull;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.currentIndexindex;this.updateCarousel();}next(){this.currentIndex(this.currentIndex1)%this.totalSlides;this.updateCarousel();}prev(){this.currentIndex(this.currentIndex-1this.totalSlides)%this.totalSlides;this.updateCarousel();}updateCarousel(){// 移动轮播图this.inner.style.transformtranslateX(-${this.currentIndex*100}%);// 更新指示器this.indicators.forEach((indicator,index){indicator.classList.toggle(active,indexthis.currentIndex);});}startAutoPlay(){this.autoPlayIntervalsetInterval(()this.next(),3000);}stopAutoPlay(){clearInterval(this.autoPlayInterval);}resetAutoPlay(){this.stopAutoPlay();this.startAutoPlay();}}// 初始化轮播图constcarouselnewCarousel(document.querySelector(.carousel));二、购物车功能2.1 商品列表 HTMLdivclassproductsdivclassproduct-carddata-id1data-nameiPhone 15data-price5999imgsrciphone.jpgaltiPhoneh3iPhone 15/h3pclassprice¥5999/pbuttonclassadd-to-cart加入购物车/button/divdivclassproduct-carddata-id2data-nameMacBook Prodata-price14999imgsrcmacbook.jpgaltMacBookh3MacBook Pro/h3pclassprice¥14999/pbuttonclassadd-to-cart加入购物车/button/div/div!-- 购物车图标 --divclasscart-iconspanclasscart-count0/span/div2.2 购物车 JavaScriptclassShoppingCart{constructor(){this.cartJSON.parse(localStorage.getItem(cart))||[];this.cartCountdocument.querySelector(.cart-count);this.init();}init(){this.bindEvents();this.updateCartUI();}bindEvents(){document.querySelectorAll(.add-to-cart).forEach(btn{btn.addEventListener(click,(e){constcarde.target.closest(.product-card);constproduct{id:parseInt(card.dataset.id),name:card.dataset.name,price:parseFloat(card.dataset.price),quantity:1};this.addToCart(product);});});}addToCart(product){constexistingItemthis.cart.find(itemitem.idproduct.id);if(existingItem){existingItem.quantity;}else{this.cart.push(product);}this.saveCart();this.updateCartUI();this.showNotification(${product.name}已加入购物车);}removeFromCart(productId){this.cartthis.cart.filter(itemitem.id!productId);this.saveCart();this.updateCartUI();}updateQuantity(productId,quantity){constitemthis.cart.find(itemitem.idproductId);if(item){item.quantityMath.max(0,quantity);if(item.quantity0){this.removeFromCart(productId);}else{this.saveCart();this.updateCartUI();}}}getTotalCount(){returnthis.cart.reduce((sum,item)sumitem.quantity,0);}getTotalPrice(){returnthis.cart.reduce((sum,item)sumitem.price*item.quantity,0);}saveCart(){localStorage.setItem(cart,JSON.stringify(this.cart));}updateCartUI(){this.cartCount.textContentthis.getTotalCount();}showNotification(message){// 创建通知元素constnotificationdocument.createElement(div);notification.classNamenotification;notification.textContentmessage;notification.style.cssTextposition: 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);}}// 初始化购物车constcartnewShoppingCart();三、知识点回顾知识点应用Class封装轮播图和购物车逻辑DOM 操作更新轮播图位置、购物车数量事件委托商品添加按钮的事件处理LocalStorage购物车数据持久化定时器轮播图自动播放CSS Transform轮播图滑动动画四、课后作业给轮播图添加触摸滑动支持移动端实现购物车详情弹窗可以修改数量添加商品收藏功能 hearts 图标有问题欢迎评论区留言大家一起讨论标签JavaScript | 实战项目 | 电商网站 | 轮播图 | 购物车 | DOM操作