javascript详解实现购物车完整功能(附效果图,完整代码)

前言:
我们肯定都很熟悉商品购物车这一功能,每当我们在某宝某东上购买商品的时候,看中了哪件商品,就会加入购物车中,最后结算。购物车这一功能,方便消费者对商品进行管理,可以添加商品,删除商品,选中购物车中的某一项或几项商品,最后商品总价也会随着消费者的操作随着变化。

一、基本功能

  1. 添加商品到购物车
  2. 移出购物车中的商品
  3. 选中某个商品,动态更新结算价格
  4. 商品数量增加与减少
  5. 全选、反选,动态更新结算价格

二、效果

1.首页

包含商品列表,加入购物车按钮,动态添加商品到购物车

在这里插入图片描述

2.添加购物车

点击按钮,实现加入购物车功能,商品移入购物车列表项

在这里插入图片描述

3.单选或多选商品

点击左侧选择框,选择商品,并动态更新总价

在这里插入图片描述

4.全选或反选

点击上方左侧按钮,实现全选,反选功能,并动态更新价格

在这里插入图片描述


在这里插入图片描述

5.删除购物车

点击右侧删除按钮,出现提示框,点击确定,删除购物车的商品,并动态更新价格

在这里插入图片描述


在这里插入图片描述

三、实现思路

1、用html实现内容
部分关键代码如下,完整代码见末尾

<div id="car" class="car">

                <div class="head_row hid">
                    <div class="check left"> <i onclick="checkAll()">√</i></div>
                    <div class="img left">&nbsp;&nbsp;全选</div>
                    <div class="name left">商品名称</div>
                    <div class="price left">单价</div>
                    <div class="number left">数量</div>
                    <div class="subtotal left">小计</div>
                    <div class="ctrl left">操作</div>
                </div>

            </div>
            <div id="sum_area">
                <div id="pay">去结算</div>
                <div id="pay_amout">合计:<span id="price_num">0</span>元</div>
            </div>

            <div id="Box">
                <h2 class="Box_head"><span>买购物车中商品的人还买了</span></h2>
                <ul>
                </ul>
            </div>

2、用css修饰外观

3、用JavaScript(jq)设计动态效果

第一步:首先是进行html页面的设计,我用一个大的div(id=Box)将所有商品包含,商品列表中我用了ul li实现,接着采用克隆的方式,显示所有商品列表,具体实现代码如下

<div id="Box">
                <h2 class="Box_head"><span>买购物车中商品的人还买了</span></h2>
                <ul>
                </ul>
            </div>
window.onload = function() {
                var aData = [{
                        "imgurl": "img/03-car-01.png","proName": " 小米手环4 NFC版 ","proPrice": "229","proComm": "1"
                    },{
                        "imgurl": "img/03-car-02.png","proName": " Redmi AirDots真无线蓝牙耳机 ","proPrice": "99.9","proComm": "9.7"
                    },{
                        "imgurl": "img/03-car-03.png","proName": " 米家蓝牙温湿度计 ","proPrice": "65","proComm": "1.3"
                    },{
                        "imgurl": "img/03-car-04.png","proName": " 小米小爱智能闹钟 ","proPrice": "149","proComm": "1.1"
                    },{
                        "imgurl": "img/03-car-05.png","proName": "米家电子温湿度计Pro  ","proPrice": "750","proComm": "0.3"
                    },{
                        "imgurl": "img/03-car-06.png","proName": " 小米手环3 NFC版 Pro  ","proPrice": "199","proComm": "3.3"
                    },{
                        "imgurl": "img/03-car-07.png","proName": " 小米手环3 / 4 通用腕带","proPrice": "19.9","proComm": "1.2"
                    },{
                        "imgurl": "img/03-car-08.png","proName": "  米家温湿度传感器 ","proPrice": "45","proComm": "0.6"
                    },{
                        "imgurl": "img/03-car-09.png","proName": "  米家电子温湿度计Pro 3个装  ","proPrice": "207",{
                        "imgurl": "img/03-car-10.png","proName": " 小米手环3 ","proComm": "7.2"
                    }
                ];
                var oBox = document.getElementById("Box");//商品列表所在的div
                var oUl = document.getElementsByTagName("ul")[0];//商品列表所在的ul
                //遍历所有商品
                for (var i = 0; i < aData.length; i++) {
                    var oLi = document.createElement("li");
                    var data = aData[i];
                    oLi.innerHTML += ‘<div class="pro_img"><img src="‘ + data["imgurl"] + ‘" width="150" height="150"></div>‘;
                    oLi.innerHTML += ‘<h3 class="pro_name"><a href="#">‘ + data["proName"] + ‘</a></h3>‘;
                    oLi.innerHTML += ‘<p class="pro_price">‘ + data["proPrice"] + ‘元</p>‘;
                    oLi.innerHTML += ‘<p class="pro_rank">‘ + data["proComm"] + ‘万人好评</p>‘;
                    oLi.innerHTML += ‘<div class="add_btn">加入购物车</div>‘;
                    oUl.appendChild(oLi);

                }

第二步:给添加购物车按钮添加事件

var aBtn = getClass(oBox,"add_btn");//获取Box下的所有添加购物车按钮
                var number = 0;//初始化商品数量
                for (var i = 0; i < aBtn.length; i++) {
                    number++;
                    aBtn[i].index = i;
                    aBtn[i].onclick = function() {
                        var oDiv = document.createElement("div");
                        var data = aData[this.index];
                        oDiv.className = "row hid";
                        oDiv.innerHTML += ‘<div class="check left"> <i class="i_check" id="i_check" onclick="i_check()" >√</i></div>‘;
                        oDiv.innerHTML += ‘<div class="img left"><img src="‘ + data["imgurl"] + ‘" width="80" height="80"></div>‘;
                        oDiv.innerHTML += ‘<div class="name left"><span>‘ + data["proName"] + ‘</span></div>‘;
                        oDiv.innerHTML += ‘<div class="price left"><span>‘ + data["proPrice"] + ‘元</span></div>‘;
                        oDiv.innerHTML +=‘ <div class="item_count_i"><div class="num_count"><div class="count_d">-</div><div class="c_num">1</div><div class="count_i">+</div></div> </div>‘
                        oDiv.innerHTML += ‘<div class="subtotal left"><span>‘ + data["proPrice"] + ‘元</span></div>‘
                        oDiv.innerHTML += ‘<div class="ctrl left"><a href="javascript:;">×</a></div>‘;
                        oCar.appendChild(oDiv);
            }
                }

第三步:给商品数量增加减少的按钮添加事件

//获取所有的数量加号按钮
var i_btn = document.getElementsByClassName("count_i");
                        for (var k = 0; k < i_btn.length; k++) {
                            i_btn[k].onclick = function() {
                                bt = this;
                                //获取小计节点
                                at = this.parentElement.parentElement.nextElementSibling;
                                //获取单价节点
                                pt = this.parentElement.parentElement.prevIoUsElementSibling;
                                //获取数量值
                                node = bt.parentNode.childNodes[1];
                                console.log(node);
                                num = node.innerText;
                                num = parseInt(num);
                                num++;
                                node.innerText = num;
                                //获取单价
                                price = pt.innerText;
                                price = price.substring(0,price.length - 1);
                                //计算小计值
                                at.innerText = price * num + "元";
                                //计算总计值
                                getAmount();
                            }
                        }
                        //获取所有的数量减号按钮
                        var d_btn = document.getElementsByClassName("count_d");
                        for (k = 0; k < i_btn.length; k++) {
                            d_btn[k].onclick = function() {
                                bt = this;
                                //获取小计节点
                                at = this.parentElement.parentElement.nextElementSibling;
                                //获取单价节点
                                pt = this.parentElement.parentElement.prevIoUsElementSibling;
                                //获取c_num节点
                                node = bt.parentNode.childNodes[1];
                                num = node.innerText;
                                num = parseInt(num);
                                if (num > 1) {
                                    num--;
                                }
                                node.innerText = num;
                                //获取单价
                                price = pt.innerText;
                                price = price.substring(0,price.length - 1);
                                //计算小计值     
                                at.innerText = price * num + "元";
                                //计算总计值
                                getAmount();
                            }
                        }

第四步:删除某个商品

//获取删除按钮,并添加事件
var delBtn = oDiv.lastChild.getElementsByTagName("a")[0];
                        delBtn.onclick = function() {
                            var result = confirm("确定删除吗?");
                            if (result) {
                                oCar.removeChild(oDiv);
                                number--;
                                getAmount();
                            }
                        }

第五步:全选
通过类名添加删除,实现选中和非选中功能

var index = false;
            function checkAll() {
                var choose = document.getElementById("car").getElementsByTagName("i");
                // console.log(choose);
                if (choose.length != 1) {
                    for (i = 1; i < choose.length; i++) {
                        if (!index) {
                            choose[0].classList.add("i_acity2")
                            choose[i].classList.add("i_acity");
                        } else {
                            choose[i].classList.remove("i_acity");
                            choose[0].classList.remove("i_acity2")
                        }
                    }
                    index = !index;
                }
                getAmount();
            }

第六步:单选
选中某个或多个商品,首先判断选中状态,然后通过类名添加删除,实现选中和非选中功能

//获取选中框
var check = oDiv.firstChild.getElementsByTagName("i")[0];
                        check.onclick = function() {
                            // console.log(check.className);
                            if (check.className == "i_check i_acity") {
                                check.classList.remove("i_acity");

                            } else {
                                check.classList.add("i_acity");
                            }
                            getAmount();
                        }

第七步:动态更新总价

//进行价格合计
            function getAmount() {
                //获取选中的选择框
                ns = document.getElementsByClassName("i_acity");
                //初始化总价
                sum = 0;
                //选中框
                document.getElementById("price_num").innerText = sum;
                for (y = 0; y < ns.length; y++) {
                    //小计
                    amount_info = ns[y].parentElement.parentElement.lastElementChild.prevIoUsElementSibling;
                    num = parseInt(amount_info.innerText);
                    sum += num;
                    document.getElementById("price_num").innerText = sum;
                }
            }

四、完整代码实现

注意:图片地址请自行修改
在线演示地址点击进入在线演示
附上下载地址,可以直接运行点击进入下载地址

<!DOCTYPE html>
<html>
    <head>
        <Meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="css/help-center.css" />
        <title>我的购物车</title>

        <style>
            * {
        margin: 0;
        padding: 0;
        font-family: "微软雅黑";
        list-style: none;
        color: #666;
        text-decoration: none;
        font-size: 14px;
    }
    body {
        background: #f5f5f5;
        height: 100%;
    }
    .header{
    font-size: 12px;
    border-bottom: 2px solid #ff6700;
    background: #fff;
    color: #b0b0b0;
    position: relative;
    z-index: 20;
    height: 100px;
}
    .header .container {
    position: relative;
    width: 1226px;
    margin-right: auto;
    margin-left: auto;
}
 .header .container .header-logo {
    width: 93px;
    margin-top: 26px;
}

 .logo {
    width: 48px;
    height: 48px;
    position: relative;
    display: block;
    width: 55px;
    height: 55px;
    overflow: hidden;
    background-color: #ff6700;
    }
    .header-title {
    float: left;
    margin-top: 26px;
    font-size: 12px;
    }
    .topbar-info {
    margin-top: 30px;
    line-height: 40px;
}
    .link {
    padding: 0 5px;
    color: #757575;
    text-decoration: none;
    }
    .hid {
        overflow: hidden;
    }
    .left {
        float: left;
    }
    .Box_head{
    position: relative;
    margin: 0;
    height: 50px;
    font-size: 30px;
    font-weight: 400;
    color: #757575;
    border-top: 1px solid #e0e0e0;
  }
  .Box_head span{
  position: absolute;
    top: -20px;
    left: 372px;
    height: 40px;
    width: 482px;
    line-height: 40px;
    text-align: center;
    display: block;
    background-color: #f5f5f5;
    font-size: 30px;
    }
    #Box {
        width:1240px;
        margin: 20px auto;
    }
    #Box ul {
        margin-right: -14px;
        overflow: hidden;
    }
    #Box li {
        width: 234px;
        float: left;
        margin-right: 14px;
        padding: 24px 0 20px;
        background: #FFF;
        text-align: center;
        position: relative;
        cursor: pointer;
        margin-bottom:14px;
    }
    .pro_img {
        width: 150px;
        height: 150px;
        margin: 0 auto 18px;
    }
    .pro_name {
        display: block;
        text-overflow: ellipsis;
        white-space: Nowrap;
        overflow: hidden;
        font-weight: 400;
    }
    .pro_name a {
        color: #333;
    }
    .pro_price {
        color: #ff6700;
        margin: 10px;
    }
    .pro_rank {
        color: #757575;
        margin: 10px;
    }
    #Box li:hover .add_btn {
        display: block;
    }
    #Box li:hover .pro_rank {
        opacity: 0;
    }
    #Box li .add_btn:hover {
        background-color: #f60;
        color: white;
    }

    .add_btn {
        height: 22px;
        position: absolute;
        width: 122px;
        bottom: 28px;
        left: 50%;
        margin-left: -61px;
        line-height: 22px;
        display: none;
        color: #F60;
        font-size: 12px;
        border: 1px solid  #f60;
    }
    .car {
        width: 1240px;
        margin: 20px auto;
        background: #FFF;
    }
    .car .check{
        width: 50px;

    }
    .car .check i{
        color: #fff;
        display: inline-block;

        width: 18px;
        height: 18px;
        line-height: 18px;
        border: 1px solid #e0e0e0;
        margin-left: 24px;
        background-color: #fff;
        font-size: 16px;
        text-align: center;
        vertical-align: middle;
        position: relative;
        top: -1px;
        cursor: pointer;
        font-family: "iconfont";
    }
    .i_acity {

        border-color: #ff6700 !important;
        background-color: #ff6700 !important;
    }
    .car .img {
        width: 190px;
    }
    .car .img img {
        display: block;
        width: 80px;
        height: 80px;
        margin: 3px auto;
    }
    .car .name {
        width: 300px;
    }
    .car .name span {
        line-height: 1;
        margin-top: 8px;
        margin-bottom: 8px;
        font-size: 18px;
        font-weight: normal;
        text-overflow: ellipsis;
        white-space: Nowrap;
        overflow: hidden;
    }
    .car .price {
        width: 144px;
        text-align: right;
        padding-right: 84px;
    }
    .car .price span {
        color: #ff6700;
        font-size: 16px;
    }
    .car .number{
        width: 150px;
    }
    .car .subtotal{
        width: 130px;

    }
    .car .ctrl {
        width: 105px;
        padding-right:25px;
        text-align: center;
    }
    .car .ctrl a {
        font-size: 20px;
        cursor: pointer;
        display: block;
        width: 26px;
        height: 26px;
        margin: 30px auto;
        line-height: 26px;
    }
    .car .ctrl a:hover {
        color: #FFF;
        background: #ff6700;
        border-radius: 50%;
    }
    .head_row {
        height: 70px;
        line-height: 70px;
    }
    .head_row,.row {
        border-bottom: solid 1px #e0e0e0;
    }
    .row {
        height: 86px;
        line-height:86px;
        padding: 15px 0;
        margin: 0px;
    }
    #sum_area{
        width:1240px;
        height: 60px;
        background: white;
        margin: 20px auto;
    }
    #sum_area #pay{
        width:250px;
        height:60px;
        text-align: center;
        float: right;
        line-height: 60px;
        font-size: 19px;
        background: #FF4B00;
        color: white;
    }
    #sum_area #pay_amout{
        width:250px;
        height:60px;
        text-align: center;
        float: right;
        line-height: 60px;
        font-size: 16px;
        color:#FF4B00 ;
    }
    #sum_area #pay_amout #price_num{
        width:100px;
        height: 60px;
        font-size: 25px;
        color:#FF4B00 ;
    /*  float: left;*/
    }

    .item_count_i{
        height: 85px;
        width:10%;
        /*border: 1px solid black;*/
        float: left;
        margin-right: 25px;
    }
    .num_count{
        width:150px;
        height:40px;
        border: 1.2px solid #E0E0E0;
        float:right;
        margin-top: 21px;

    }
    .count_i{
        width:30%;
        height:40px;
        line-height: 40px;
        float: left;
        text-align: center;
        font-size:21px;
        color: #747474;
    }
    .count_i:hover{
        width:30%;
        height:40px;
        line-height: 40px;
        float: left;
        text-align: center;
        font-size:21px;
        color: #747474;
        background: #E0E0E0;
        cursor: pointer;
    }
    .c_num{
        width:40%;
        height:40px;
        line-height: 40px;
        float: left;
        text-align: center;
        font-size:16px;
        color: #747474;
    }
    .count_d{
        width:30%;
        height:40px;
        line-height: 40px;
        float: left;
        text-align: center;
        font-size:25px;
        color: #747474;
    }
    .count_d:hover{
        width:30%;
        height:40px;
        line-height: 40px;
        float: left;
        text-align: center;
        font-size:25px;
        color: #747474;
        background: #E0E0E0;
        cursor: pointer;
    }
    .i_acity2 {
        border-color: #ff6700 !important;
        background-color: #ff6700 !important;
    }

</style>
    </head>
    <body>
        <script>
            window.onload = function() {
                var aData = [{
                        "imgurl": "img/03-car-01.png","proComm": "7.2"
                    }
                ];
                var oBox = document.getElementById("Box");
                var oCar = document.getElementById("car");
                var oUl = document.getElementsByTagName("ul")[0];

                for (var i = 0; i < aData.length; i++) {
                    var oLi = document.createElement("li");
                    var data = aData[i];

                    oLi.innerHTML += ‘<div class="pro_img"><img src="‘ + data["imgurl"] + ‘" width="150" height="150"></div>‘;
                    oLi.innerHTML += ‘<h3 class="pro_name"><a href="#">‘ + data["proName"] + ‘</a></h3>‘;
                    oLi.innerHTML += ‘<p class="pro_price">‘ + data["proPrice"] + ‘元</p>‘;
                    oLi.innerHTML += ‘<p class="pro_rank">‘ + data["proComm"] + ‘万人好评</p>‘;
                    oLi.innerHTML += ‘<div class="add_btn">加入购物车</div>‘;
                    oUl.appendChild(oLi);

                }
                var aBtn = getClass(oBox,"add_btn");//获取Box下的所有添加购物车按钮
                var number = 0;//初始化商品数量
                for (var i = 0; i < aBtn.length; i++) {
                    number++;
                    aBtn[i].index = i;
                    aBtn[i].onclick = function() {
                        var oDiv = document.createElement("div");
                        var data = aData[this.index];
                        oDiv.className = "row hid";
                        oDiv.innerHTML += ‘<div class="check left"> <i class="i_check" id="i_check" onclick="i_check()" >√</i></div>‘;
                        oDiv.innerHTML += ‘<div class="img left"><img src="‘ + data["imgurl"] + ‘" width="80" height="80"></div>‘;
                        oDiv.innerHTML += ‘<div class="name left"><span>‘ + data["proName"] + ‘</span></div>‘;
                        oDiv.innerHTML += ‘<div class="price left"><span>‘ + data["proPrice"] + ‘元</span></div>‘;
                        oDiv.innerHTML +=‘ <div class="item_count_i"><div class="num_count"><div class="count_d">-</div><div class="c_num">1</div><div class="count_i">+</div></div> </div>‘
                        oDiv.innerHTML += ‘<div class="subtotal left"><span>‘ + data["proPrice"] + ‘元</span></div>‘
                        oDiv.innerHTML += ‘<div class="ctrl left"><a href="javascript:;">×</a></div>‘;
                        oCar.appendChild(oDiv);
                        var flag = true;
                        var check = oDiv.firstChild.getElementsByTagName("i")[0];
                        check.onclick = function() {
                            // console.log(check.className);
                            if (check.className == "i_check i_acity") {
                                check.classList.remove("i_acity");

                            } else {
                                check.classList.add("i_acity");
                            }
                            getAmount();
                        }
                        var delBtn = oDiv.lastChild.getElementsByTagName("a")[0];
                        delBtn.onclick = function() {
                            var result = confirm("确定删除吗?");
                            if (result) {
                                oCar.removeChild(oDiv);
                                number--;
                                getAmount();
                            }
                        }
                        var i_btn = document.getElementsByClassName("count_i");
                        for (var k = 0; k < i_btn.length; k++) {
                            i_btn[k].onclick = function() {
                                bt = this;
                                //获取小计节点
                                at = this.parentElement.parentElement.nextElementSibling;
                                //获取单价节点
                                pt = this.parentElement.parentElement.prevIoUsElementSibling;
                                //获取数量值
                                node = bt.parentNode.childNodes[1];
                                console.log(node);
                                num = node.innerText;
                                num = parseInt(num);
                                num++;
                                node.innerText = num;
                                //获取单价
                                price = pt.innerText;
                                price = price.substring(0,price.length - 1);
                                //计算小计值     
                                at.innerText = price * num + "元";
                                //计算总计值
                                getAmount();
                            }
                        }

                        delBtn.onclick = function() {
                            var result = confirm("确定删除吗?");
                            if (result) {
                                oCar.removeChild(oDiv);
                                number--;
                                getAmount();
                            }
                        }

                    }
                }

            }

            function getClass(oBox,tagname) {
                var aTag = oBox.getElementsByTagName("*");
                var aBox = [];
                for (var i = 0; i < aTag.length; i++) {
                    if (aTag[i].className == tagname) {
                        aBox.push(aTag[i]);
                    }
                }
                return aBox;
            }

            var index = false;
            function checkAll() {
                var choose = document.getElementById("car").getElementsByTagName("i");
                // console.log(choose);
                if (choose.length != 1) {
                    for (i = 1; i < choose.length; i++) {
                        if (!index) {
                            choose[0].classList.add("i_acity2")
                            choose[i].classList.add("i_acity");
                        } else {
                            choose[i].classList.remove("i_acity");
                            choose[0].classList.remove("i_acity2")
                        }
                    }
                    index = !index;
                }
                getAmount();
            }

            //进行价格合计
            function getAmount() {
                // console.log(ys);
                ns = document.getElementsByClassName("i_acity");
                console.log(ns);
                sum = 0;
                //选中框
                document.getElementById("price_num").innerText = sum;
                for (y = 0; y < ns.length; y++) {
                    //小计
                    amount_info = ns[y].parentElement.parentElement.lastElementChild.prevIoUsElementSibling;
                    num = parseInt(amount_info.innerText);
                    sum += num;
                    document.getElementById("price_num").innerText = sum;
                }
            }
        </script>
        </head>
        <body>
            <div class="header">
                <div class="container">
                    <div class="header-logo">
                        <a class="logo ir" href="" title="小米官网">小米官网</a>
                    </div>
                    <div class="header-title" id="J_miniHeaderTitle">
                        <h2 style="font-size: 30px;">我的购物车</h2>
                    </div>
                    <div class="topbar-info" id="J_userInfo">
                        <a class="link" href="http://www.weichufeng.cn/login.jsp">登录</a><span class="sep">|</span><a class="link" href="http://www.weichufeng.cn/regist.jsp">注册</a></div>
                </div>
            </div>

            <div id="car" class="car">

                <div class="head_row hid">
                    <div class="check left"> <i onclick="checkAll()">√</i></div>
                    <div class="img left">&nbsp;&nbsp;全选</div>
                    <div class="name left">商品名称</div>
                    <div class="price left">单价</div>
                    <div class="number left">数量</div>
                    <div class="subtotal left">小计</div>
                    <div class="ctrl left">操作</div>
                </div>

            </div>
            <div id="sum_area">
                <div id="pay">去结算</div>
                <div id="pay_amout">合计:<span id="price_num">0</span>元</div>
            </div>

            <div id="Box">
                <h2 class="Box_head"><span>买购物车中商品的人还买了</span></h2>
                <ul>
                </ul>
            </div>

        </body>
</html>

感谢您的阅读,有什么问题或者意见欢迎您提出

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...