JavaScript 仿淘宝购物车案例

2021/12/31 14:07:13

本文主要是介绍JavaScript 仿淘宝购物车案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 加入购物车

页面

页面结构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物</title>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <!-- 页面结构 -->
   <ul class="cont">
       <!-- <li>
           <div class="productimg">
               <img src="./img/小米电风扇.jpg" alt="重新加载">
           </div>
           <div class="producttext">
               <div class="text1">米家落地扇</div>
               <div class="text2">7羽叶大风量丨智能控制丨12米远距送风丨台地两用</div>
               <div class="price">
                   <span class="newprice">199元</span>
                   <span class="oldprice"><span><del>209元</del></span>
               </div>
               <input type="button" value="加入购物车" class="btn">
           </div>
       </li> -->
   </ul>
   <a href="./cart.html">
   <input type="button" value="我的购物车" class="mycart">
    </a>
   <script src="./js/index.js"></script>
</body>
</html>

css

*{
    margin: 0;
    padding: 0;
    list-style: none;
}
.cont{
    width: 1660px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    margin: 20px 20px;
}
.cont li{
    display: flex;
    width: 500px;
    height: 300px;
    margin: 20px 20px;
    flex-direction: row;
    flex-wrap: nowrap;
    border: solid 1px #ccc;
}
.productimg img{
    width: 200px;
    height: 300px;
}
.producttext{
    display: flex;
    margin-left: 10px;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: space-evenly;
    align-content: center;
}
.text1{
    font-size: 20px;
}
.text2{
    width: 260px;
    font-size: 16px;
    color: grey;
    
}

.newprice,.oldprice{
    width: 100px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    margin-left: 20px;
}
.newprice{
    color: tomato;
    font-size: 20px;
}
.oldprice{
    color: grey;
    font-size: 14px;
}
.btn{
    width: 150px;
    height: 30px;
    background-color: red;
    color: white;
    border: none;
    border-radius:10px ;
}

js

// 数据结构
var merchandise={
    Id:[0,1,2,3,4,5,6],
    Img:["./img/小米电风扇.jpg","./img/小米路由器.jpg","./img/小米旅行箱.png","./img/小米燃气灶.jpg","./img/小米牙膏.jpg","./img/小米音箱.jpg"],
    merchandiseName:["小米电风扇","小米路由器","小米旅行箱","小米燃气灶","小米牙膏","小米音箱"],
    Text:["7羽叶大风量丨智能控制丨12米远距送风丨台地两用","安全防蹭网 | 支持 IPv6* | 儿童安全上网 | 专为小米智能家居优化","可选尺寸:20英寸、24英寸,环保材料,轻便重量,坚韧有型,4色可选","4200W大火力,猛火爆炒无压力 / 三重补齐设计,节能省时省气 / 10种安全保障 / 230°无级调火","0添加色素防腐剂 / 选用进口研磨剂 / 不伤牙釉质 / 加固牙齿硬度 / 长效冰爽口气","内置小爱同学,快速唤醒 / 立式造型,快捷操作 / 蓝牙5.0,更好兼容性 / Type-C 接口,6小时续航"],
    newprice:[479,129,199,699,12.9,49],
    oldprice:[499,159,259,899,15.9,69]
}
// 获取相应的容器
var cont=document.querySelector(".cont");
// 渲染页面
for (let i = 0; i < merchandise.Img.length; i++) {
    var list=document.createElement("li");
    list.innerHTML=` 
    <div class="productimg" data-cid="${merchandise.Id[i]}">
    <img src="${merchandise.Img[i]}" alt="重新加载">
    </div>
    <div class="producttext">
    <div class="name">${merchandise.merchandiseName[i]}</div>
    <div class="text">${merchandise.Text[i]}</div>
    <div class="price">
        <span class="newprice">${merchandise.newprice[i]}元</span>
        <span class="oldprice"><span><del>${merchandise.oldprice[i]}元</del></span>
    </div>
    <input type="button" value="加入购物车" class="btn">
</div>`
   cont.appendChild(list)
}
// 每个加入购物按钮的事件
//获取相应的按钮
var btnArr=document.querySelectorAll(".btn");
// 创建一个储存商品的地址
var cart={
    cartId:[],
    cartName:[],
    cartImg:[],
    cartText:[],
    cartNewprice:[],
    cartOldprice:[],
    cartNum:[],
    check:[]
};
// 购物车缓存初始化
var shoppingCarInfo = localStorage.getItem("cartName");
if(!shoppingCarInfo){
    localStorage.setItem("cartName", JSON.stringify([]));
}
// 获取相应的数据
var shopping=JSON.parse(localStorage.getItem("cartName"));
if (shopping==0) {
    gettingData();  
}else{
    getting();
}
 


// 工具函数
function gettingData(){
    for (let j = 0; j < btnArr.length; j++) {
        btnArr[j].addEventListener("click",()=>{
        // 获取父级节点的信息
        var father=btnArr[j].parentNode.parentNode;  
        var cid=father.querySelector(".productimg").dataset.cid;
        // 判断里面有没有这个东西没有才往里面添加,有则商品数量加一
        if(cart.cartId.includes(cid)){
            var num=cart.cartId.indexOf(cid)
            cart.cartNum[num]=cart.cartNum[num]+1;
            // 把获取的数据存起来
        localStorage.setItem("cartName",JSON.stringify(cart));
        }else{
            cart.cartId.push(cid);
            cart.cartName.push(father.querySelector(".name").innerHTML);
            cart.cartImg.push(father.querySelector("img").getAttribute("src"));
            cart.cartText.push(father.querySelector(".text").innerHTML);
            cart.cartNewprice.push(father.querySelector(".newprice").innerHTML);
            cart.cartOldprice.push(father.querySelector(".oldprice>span>del").innerHTML);
            cart.cartNum.push(1);
            cart.check.push(1);
            // 把获取的数据存起来
            localStorage.setItem("cartName",JSON.stringify(cart));
            }
        })
    }
}
function getting(){
    shopping=JSON.parse(localStorage.getItem("cartName"));
    for (let j = 0; j < btnArr.length; j++) {
        btnArr[j].addEventListener("click",()=>{
        // 获取父级节点的信息
        father=btnArr[j].parentNode.parentNode;  
        cid=father.querySelector(".productimg").dataset.cid;
        // 判断里面有没有这个东西没有才往里面添加,有则商品数量加一
        if(shopping.cartId.includes(cid)){
             num=shopping.cartId.indexOf(cid)
            shopping.cartNum[num]=shopping.cartNum[num]+1;
            // 把获取的数据存起来
        localStorage.setItem("cartName",JSON.stringify(shopping));
        }else{
            shopping.cartId.push(cid);
            shopping.cartName.push(father.querySelector(".name").innerHTML);
            shopping.cartImg.push(father.querySelector("img").getAttribute("src"));
            shopping.cartText.push(father.querySelector(".text").innerHTML);
            shopping.cartNewprice.push(father.querySelector(".newprice").innerHTML);
            shopping.cartOldprice.push(father.querySelector(".oldprice>span>del").innerHTML);
            shopping.cartNum.push(1);
            shopping.check.push(1);
            // 把获取的数据存起来
            localStorage.setItem("cartName",JSON.stringify(shopping));
            }
        })
    }
} 



购物车页码结构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <link rel="stylesheet" href="./css/cart.css">
</head>
<body>
    <ul class="ullist">
        <!-- <li class="list">
           <input type="checkbox" name="" id="" class="ckecks">
           <div class="cartimg">
               <img src="./img/小米旅行箱.png" alt="加载失败">
           </div>
           <div class="carttext">
               <div class="cartname">电风扇</div>
               <div class="carttext1">非常棒</div>
           </div>
           <div class="cartprice">
                <span class="oldprice"><del>原价:209元</del></span>
                <span class="newprice">现价:199元</span>
           </div>
           <div class="num">
               <button class="libtn1">+</button>
               <span>1</span>       
               <button class="libtn2">-</button>
           </div>
        </li>
        <div class="del">删除</div> -->
    </ul>
    <div class="end">
        <div class="cont">
            <input type="checkbox" name="" id="" class="checkboxes">全选
            <span class="contbtn2">删除</span>
        </div>
        <a href="./index.html">
        <input type="button" value="继续购物">
        </a>
        <div class="statement">
            <span class="sumnum">总数:0</span>
            <span class="sumprice">总价:0</span>
            <span class="play">去结算</span>
        </div>
    </div>
    <script src="./js/cart.js"></script>
</body>
</html>

一点点css

*{
    margin: 0;
    padding: 0;
    list-style: none;
}

.ullist li{
    display: flex;  
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-evenly;
    align-items: stretch;

    width: 1200px;
    height: 200px;
    border-bottom: solid 1px #ccc;
    margin: 40px 40px;
}
.ckecks{
    margin-top: 160px;
}
.cartimg{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: center;
}
.cartimg img{
    width: 100px;
    height: 100px;
    display: block;
}
.carttext{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
}
.cartprice{
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: center;
    align-items: center;
}

.num,.del{
    line-height: 200px;
}
.end{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
    margin: 20px 40px;
    width: 1200px;
    height: 50px;
}
.cont{
    margin-left: 125px;
}
.statement{
    margin: 0 125px;
}
.contbtn2{
   margin: 0 80px; 
}
.sumnum{
    margin:0 80px;
}

写到这里就开始头疼,逻辑可能有点乱

// 取数据
var arr=JSON.parse(localStorage.getItem("cartName"));
// 渲染页面
var ullist=document.querySelector(".ullist");
if(arr.length!=0){
    make();
// 计算总数和总价
getTotalPriceAndTotalNum();
}

// 全选
var list=document.querySelectorAll(".ullist>li");
var ckecks=document.querySelectorAll(".checkbox:checked");
var checkboxes=document.querySelector(".checkboxes");
Alls();
for (let i = 0; i < list.length; i++) {
    list[i].addEventListener("change",()=>{
       Alls();
    })
    
} 
var index=1;
checkboxes.addEventListener("click",()=>{
    var check=document.querySelectorAll(".checkbox")
  if (index%2!=0) {
        for (let i = 0; i < check.length; i++) {
            check[i].checked=false;  
            shopping();
        } 
    }else{
        for (let i = 0; i < check.length; i++) {
            check[i].checked=true;  
            getTotalPriceAndTotalNum()
        }
    }
    
    index++;
})




// 单删除
var delArr=document.querySelectorAll(".del");
for (let j = 0; j < delArr.length; j++) {
    delArr[j].addEventListener("click",()=>{
        delArr[j].parentNode.remove();
        dels(delArr[j].parentNode.querySelector(".cartimg").dataset.cid);
        console.log(delArr[j].parentNode.querySelector(".cartimg").dataset.cid);
        console.log("单次删除"+arr);
        list=document.querySelectorAll(".ullist>li");
        if (list.length==0) {
            checkboxes.checked=false
        }
    });
} 
var contbtn2=document.querySelector(".contbtn2");
// 多个删除
contbtn2.addEventListener("click",()=>{
    var flag=confirm("这些东西怎么牛逼,确定不要了吗?");
       if (flag) {
        var listes=document.querySelectorAll(".ullist>li");
        var iteamCkeks=document.querySelectorAll(".checkbox:checked");

           if (iteamCkeks.length==listes.length) {//全删
            delAll();
            ullist.remove(); 
            shopping();
            localStorage.setItem("cartName",JSON.stringify(arr));
           }else{
            for (let i = 0; i <iteamCkeks.length; i++) {
            //    console.log(iteamCkeks[i].parentNode.querySelector(".cartimg").dataset.cid);
            dels(iteamCkeks[i].parentNode.querySelector(".cartimg").dataset.cid);
            listes[i].remove();
            }
           }
       }
       list=document.querySelectorAll(".ullist>li");
    if (list.length==0) {
        checkboxes.checked=false
    }
})

// })
// 商品数量
var libtn1=document.querySelectorAll(".libtn1")
var libtn2=document.querySelectorAll(".libtn2")
var num=document.querySelectorAll(".num>span")
// 数量加法
for (let i = 0; i < libtn1.length; i++) {
    libtn1[i].addEventListener("click",()=>{
        num[i].innerHTML=Number(num[i].innerHTML)+1;
        numadd(num[i].parentNode.parentNode.querySelector(".cartimg").dataset.cid);
        shopping();
    }) 
}
// 数量减法
for (let i = 0; i < libtn2.length; i++) {
    libtn2[i].addEventListener("click",()=>{
        if (num[i].innerHTML<=1) {
            dels(libtn2[i].parentNode.parentNode.querySelector(".cartimg").dataset.cid);
            num[i].parentNode.parentNode.remove();
            shopping();
            console.log(arr);
        }else{
            num[i].innerHTML=Number(num[i].innerHTML)-1;
            numsub(num[i].parentNode.parentNode.querySelector(".cartimg").dataset.cid);
            shopping();
            console.log(arr);
        }
        list=document.querySelectorAll(".ullist>li");
    if (list.length==0) {
        checkboxes.checked=false
    }
    }) 
    
}
// 工具函数

function make(){
  
    for (let i = 0; i < arr.cartId.length; i++) {
        var temp="";
        if (arr.check[i]==1) {
            temp = "checked";
        }
        var list=document.createElement("li");
        list.innerHTML=`
        <input type="checkbox" name="" id="" class="checkbox" ${temp}>   
        <div class="cartimg" data-cid="${arr.cartId[i]}">
            <img src="${arr.cartImg[i]}" alt="加载失败">
        </div>
        <div class="carttext">
            <div class="cartname">${arr.cartName[i]}</div>
            <div class="carttext1">${arr.cartText[i]}</div>
        </div>
        <div class="cartprice">
             <div class="oldprice"><span><del>原价:${arr.cartOldprice[i]}</del></span></div>
             <span class="newprice">现价:${arr.cartNewprice[i]}</span>
        </div>
        <div class="num">
            <button class="libtn1">+</button>
            <span>${arr.cartNum[i]}</span>       
            <button class="libtn2">-</button>
        </div>
        <div class="del">删除</div>
        `
          ullist.appendChild(list) 
       }
}
function getTotalPriceAndTotalNum(){
    getTotalPrice();//总价
    getTotalNum();//总量
}
function getTotalPrice(){
    var totalPrice=0;
    var temp_info=JSON.parse(localStorage.getItem("cartName"));
    for (let i = 0; i <temp_info.cartId.length; i++) {
        totalPrice+=parseInt( temp_info.cartNum[i])*parseInt( temp_info.cartNewprice[i]);
    }
    document.querySelector(".sumprice").innerHTML=`总价:${totalPrice}`
}
function  getTotalNum(){
    var totalNum=0;
    var temp_info=JSON.parse(localStorage.getItem("cartName"));
    for (let i = 0; i < temp_info.cartId.length; i++) {
       totalNum+=temp_info.cartNum[i]
    }
    document.querySelector(".sumnum").innerHTML=`总数:${totalNum}`
}
function dels(_cid){
    arr.cartId.splice(arr.cartId.indexOf(_cid),1)
    arr.cartImg.splice(arr.cartId.indexOf(_cid),1)
    arr.cartName.splice(arr.cartId.indexOf(_cid),1)
    arr.cartText.splice(arr.cartId.indexOf(_cid),1)
    arr.cartOldprice.splice(arr.cartId.indexOf(_cid),1)
    arr.cartNewprice.splice(arr.cartId.indexOf(_cid),1)
    arr.cartNum.splice(arr.cartId.indexOf(_cid),1)
    arr.check.splice(arr.cartId.indexOf(_cid),1)
    localStorage.setItem("cartName",JSON.stringify(arr));  
    shopping()      
}
function delAll(){
    arr.cartId=[];
    arr.cartImg=[];
    arr.cartName=[];
    arr.cartText=[];
    arr.cartNewprice=[];
    arr.cartOldprice=[];
    arr.cartNum=[];
    arr.check=[];
    localStorage.setItem("cartName",JSON.stringify(arr)); 
    document.querySelector(".sumnum").innerHTML=`总数:0`;
    document.querySelector(".sumprice").innerHTML=`总价:0`
}
function numadd(_num){
    console.log(arr.cartNum[0]);
    arr.cartNum[arr.cartId.indexOf(_num)]+=1
    console.log(arr.cartNum[0]);
    // console.log( arr.cartNum[arr.cartId]);
    localStorage.setItem("cartName",JSON.stringify(arr)); 
}
function numsub(_num){

    arr.cartNum[arr.cartId.indexOf(_num)]-=1
}
function Alls(){
     ckecks=document.querySelectorAll(".checkbox:checked");
    if (ckecks.length==list.length) {
        checkboxes.checked=true;  
        }else{
            checkboxes.checked=false;  
            shopping();
        }
}
function shopping(){
    var checksArr=document.querySelectorAll(".checkbox:checked");
    var nums=0;
    var sums=0;
    if(checksArr.length==0){
        document.querySelector(".sumnum").innerHTML=`总数:0`;
        document.querySelector(".sumprice").innerHTML=`总价:0`
    }else{
        for (let i = 0; i < checksArr.length; i++) {
           nums=checksArr[i].parentNode.querySelector(".num>span").innerHTML-0+nums;
           document.querySelector(".sumnum").innerHTML=`总数:${nums}`
        }
        for (let j = 0; j < checksArr.length; j++) {
            var str=checksArr[j].parentNode.querySelector(".newprice").innerHTML
            str=str.slice(3,-1);
    
            sums+=(checksArr[j].parentNode.querySelector(".num>span").innerHTML-0) *Number(str)
           document.querySelector(".sumprice").innerHTML=`总价:${sums}`
        }
    }
}



这篇关于JavaScript 仿淘宝购物车案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程