原生js 实现一个简单购物车的功能

101 阅读3分钟

购物车的功能实现

通用的html页面
  • 正在这里定义一个顶部和底部区域的页面构建都用js老实现
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>

    <div class="header">页面顶部</div>
    <div class="content">                      
    </div>
    <div class="footer">页面底部</div>
</body>
<script src="index.js"></script>
</html>
css样式
* {
    margin: 0;
    padding: 0;
}

ul,
ol,
li {
    list-style: none;
}

.header,
.footer {
    width: 1200px;
    height: 100px;
    background-color: skyblue;
    color: #fff;
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
}

.footer {
    height: 400px;
}

.content {
    width: 1200px;
    margin: 0 auto;
    padding: 10px 0;
}

.content > .top,
.content > .bottom {
    height: 50px;
    background-color: pink;
    display: flex;
    align-items: center;
}

.content > .bottom {
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 10px;
}

.content > .bottom > .totalPrice > span {
    font-size: 20px;
    color: red;
}

.content > .bottom > .btns > button {
    font-size: 18px;
    padding: 5px 10px;
    cursor: pointer;
}

.content > .top > input {
    width: 30px;
    height: 30px;
    margin: 0 15px 0 50px;
}

.content > ul {
    padding-top: 10px;
}

.content > ul > li {
    width: 100%;
    border: 1px solid #333;
    box-sizing: border-box;
    height: 100px;
    margin-bottom: 10px;

    display: flex;
}

.content > ul > li > div {
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1px solid #333;
}

.content > ul > li > div:last-child {
    border: none;
}

.content > ul > li > .show,
.content > ul > li > .status {
    width: 100px;
}

.content > ul > li > .status > input {
    width: 30px;
    height: 30px;
}

.content > ul > li > .show > img {
    width: 100%;
    height: 100%;
    display: block;
}

.content > ul > li > .price,
.content > ul > li > .sub {
    width: 200px;
    color: red;
    font-size: 20px;
}

.content > ul > li > .title {
    width: 300px;
    align-items: flex-start;
    justify-content: flex-start;
    box-sizing: border-box;
    padding: 5px;
}

.content > ul > li > .number {
    width: 230px;
}

.content > ul > li > .number > input {
    width: 50px;
    height: 30px;
    text-align: center;
    margin: 0 5px;
    border: none;
    outline: none;
    font-size: 18px;
}

.content > ul > li > .number > button {
    width: 30px;
    height: 30px;
    cursor: pointer;
}

.content > ul > li > .destory {
    flex: 1;
}

.content > ul > li > .destory > button {
    padding: 5px;
    font-size: 18px;
    cursor: pointer;
}

js样式
var cartList = [
    {
        id: 111234,
        status: false,
        pic: "https://img1.baidu.com/it/u=2511310783,721605137&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=332",
        name: "我是一个手机, 不知道是啥",
        price: 100,
        number: 3,
        total: 16,
    },
    {
        id: 123456,
        status: true,
        pic: "https://img1.baidu.com/it/u=1537709578,2453227648&fm=253&fmt=auto&app=120&f=JPEG?w=809&h=500",
        name: "我是一个电脑, 不知道是啥",
        price: 98.72,
        number: 1,
        total: 7,
    },
    {
        id: 965874,
        status: true,
        pic: "https://img2.baidu.com/it/u=3561506717,735421650&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
        name: "我是一个手纸, 不知道是啥",
        price: 356.21,
        number: 2,
        total: 22,
    },
];
var content = document.querySelector(".content")
var a
var num3
function list() {
    //清除
    content.innerHTML = ""

   
   
    var num1 = 0    //存储选中商品的数量 用来判断是否全选
    var num2 = 0    //商品的总件数
     num3 = 0    //商品的总价格

    for (let q = 0; q < cartList.length; q++) {
        if (cartList[q].status) {
            num1++
            num2 += cartList[q].number
            num3 += num2 * cartList[q].price
        }

    }
 
    // 拿到所有数据
    var str = `
    <div class="top">
    <input type="checkbox"class="check" ${num1 === cartList.length&&num1!==0 ? "checked" : ""}> 全选
    </div>
    <ul>
   
    `
    for (let i = 0; i < cartList.length; i++) {

        //创建需要的li
        str += `
        <li>
        <div class="status">
            <input type="checkbox" data-id=${cartList[i].id} class="input_s" ${cartList[i].status ? 'checked' : ""}> 
        </div>
        <div class="show">
            <img src="${cartList[i].pic}" alt="">
        </div>
        <div class="title">
        ${cartList[i].name}
        </div>
        <div class="price">
            ¥  ${cartList[i].price.toFixed(2)}
        </div>
        <div class="number">
        <button class="btn1" data-id=${cartList[i].id} >-</button>
        <input type="text" value=" ${cartList[i].number}" >
        <button class="btn2" data-id=${cartList[i].id}>+</button>
    </div>
    <div class="sub">
        ¥${(cartList[i].number * cartList[i].price).toFixed(2)}
    </div>
    <div class="destory">
        <button class="btn3" data-id=${i}>删除</button>
    </div>
    </li>
    `
    }

    str += `
    </ul>
        <div class="bottom">
        <div class="totalNum">
            总件数 : ${num2}
        </div>
        <div class="btns">
            <button class="btn4">清空购物车</button>
            <button class="btn5" data-num=${num1} data-price=${num3.toFixed(2)}>去结算</button>
            <button class="btn6" data-num=${num1}>删除所有已选中</button>
        </div>
        <div class="totalPrice">
            总价格 : ¥ <span>${num3.toFixed(2)}</span>
        </div>
        </div>
    `

    content.innerHTML = str

}
list()
// 全选功能

content.onclick = function (e) {
    if (e.target.className === "check") {

        for (let i = 0; i < cartList.length; i++) {
            cartList[i].status = e.target.checked

        }
        list()
    } else if (e.target.className === 'input_s') {

        for (let w = 0; w < cartList.length; w++) {
            if (cartList[w].id === e.target.dataset.id-0) {
                cartList[w].status = e.target.checked;

            }
        }
        list()
    }//减少商品
    else if (e.target.className === 'btn1') { 
        for (let w = 0; w < cartList.length; w++) {
            if (cartList[w].id === e.target.dataset.id-0) {
                if (cartList[w].number===1) {
                   
                    alert("没了别减了")
                    return
                }
                cartList[w].number--
             
            }
           
        }
        list()
    }
    //增加商品
    else if (e.target.className === 'btn2') { 
        for (let w = 0; w < cartList.length; w++) {
            if (cartList[w].id === e.target.dataset.id-0) {
                if (cartList[w].number===cartList[w].total) {
                   
                    alert("没了别加了")
                    return
                }
                cartList[w].number++
            }  
        }
        list()
    }
    //删除单个商品
    else if (e.target.className === 'btn3') { 
        if(confirm("确定要s删吗")){
        cartList.splice(e.target.dataset.id, 1);
        }
        list()
    }//清空购物车
    else if (e.target.className === 'btn4') { 
        if(confirm("确定要清空购物车吗")){
            cartList = []
        }
        list()
    }//去结算
    else if (e.target.className === 'btn5') { 
        if (e.target.dataset.num==="0") return alert("没有商品") 
           
        if(confirm(`总共${e.target.dataset.price}是否结算`)){
            for (let w = 0; w < cartList.length; w++) {
                if (cartList[w].status) {
                  cartList.splice(w, 1);
                  w--
                } 
            }
        }
        list()
    }//删除所有已选中
    else if (e.target.className === 'btn6') { 
        if (e.target.dataset.num==="0") return alert("没有已选中商品") 
        
        if(confirm(`确定要删除所有已选中的商品吗`)){
            for (let w = 0; w < cartList.length; w++) {
              if (cartList[w].status) {
                cartList.splice(w, 1);
                w--
              } 
              
            }
         
        }
        list()
    }
   
}