代码打包资源下载:【免费】HTML+JS+CSS移动端购物车选购界面资源-CSDN文库
关键部分说明:
UIGoods
类:
- 构造函数: 创建
UIGoods
实例时,传入商品数据g
,初始化商品的数据和选择数量。 getTotalPrice()
方法: 计算商品的总价,考虑了选择数量。isChoose()
方法: 判断是否选中该商品。increase()
方法: 增加商品的选择数量。decrease()
方法: 减少商品的选择数量,但数量不会小于 0。
class UIGoods {constructor(g) {this.data = gthis.choose = 0}getTotalPrice() {return this.data.price * this.choose}isChoose() {return this.choose > 0}increase() {this.choose++}decrease() {if (this.choose === 0) {return}this.choose--}
}
UIData
类:
- 构造函数: 初始化页面数据,包括商品列表、起送价格和配送费。
getTotalPrice()
方法: 计算购物车中所有商品的总价。increase(index)
和decrease(index)
方法: 分别用于增加和减少某个商品的选择数量。getTotalChooseNum()
方法: 获取购物车中所有商品的总选择数量。isGoodsInCar()
方法: 判断购物车中是否有商品。isStartSendPrice()
方法: 判断是否达到起送价格。isChoose(index)
方法: 判断某个商品是否被选中。
class UIData {constructor() {let uiGoods = []goods.forEach(item => {let uig = new UIGoods(item)uiGoods.push(uig)})this.uiGoods = uiGoodsthis.startSendPrice = 30this.needSendPrice = 5}getTotalPrice() {let sum = 0this.uiGoods.forEach((item, index) => {sum += item.getTotalPrice()})return sum}increase(index) {this.uiGoods[index].increase()}decrease(index) {this.uiGoods[index].decrease()}getTotalChooseNum() {let sum = 0this.uiGoods.forEach((item) => {sum += item.choose})return sum}isGoodsInCar() {return this.getTotalChooseNum() > 0}isStartSendPrice() {return this.getTotalPrice() > this.startSendPrice}isChoose(index) {return this.uiGoods[index].isChoose()}
}
UI
类:
- 构造函数: 初始化页面和事件监听。
creatHTML()
方法: 根据商品数据创建商品元素的 HTML 结构,用于初始化页面。increase(index)
和decrease(index)
方法: 用于增加和减少商品选择数量,同时更新页面显示。updateGoodsItem(index)
和updateFooter()
方法: 更新商品元素和页脚的显示状态。carAnimate()
和jump(index)
方法: 分别处理购物车动画和商品选择数量变化的跳跃抛物线动画。
class UI {constructor() {// ...(省略其他初始化和元素获取的代码)let carRect = this.doms.car.getBoundingClientRect()let jumpTarget = {x: carRect.left + carRect.width / 2,y: carRect.top + carRect.height / 5}this.jumpTarget = jumpTargetthis.creatHTML()this.updateFooter()this.listenEvent()}// ...(省略其他方法)creatHTML() {let html = ''this.uiData.uiGoods.forEach((item, index) => {html += `<div class="goods-item"><!-- ...省略商品元素的HTML结构... --></div>`})this.doms.goodsContainer.innerHTML = html}increase(index) {this.uiData.increase(index)this.updateGoodsItem(index)this.updateFooter()this.jump(index)}decrease(index) {this.uiData.decrease(index)this.updateGoodsItem(index)this.updateFooter()}// ...(省略其他方法)updateGoodsItem(index) {// 更新商品元素的显示状态// ...省略具体实现...}updateFooter() {// 更新页脚的显示状态// ...省略具体实现...}carAnimate() {this.doms.car.classList.add('animate')}jump(index) {// 商品选择数量变化的跳跃抛物线动画// ...省略具体实现...}
}
注意:
文章说明:该功能是根据“渡一前端”视频敲出来的,并不属于原创,但是转载或是翻译的连接我找不到了,所以使用的原创标签,特此说明一下。