如何用原生jS做购物车

 

 

    如何用原生jS做购物车

今天给大家分享如何用原生js做购物车,我们都逛过淘宝、京东这样购物网站,像这种购物网站,购物车是肯定少不了的 ,我们在天猫上购物,一开始一个页面有很多种商品,然后你在这里面看中了某件商品,点击之后就会跳转到详情页,详情页里有商品的详细信息,还有一个很放大镜一样的东西,可以让你看到商品的细节,还有选择数量,加入购物车,购物车里又有全选反选,商品数量修改,删除等操作,这些都是怎么实现的楞,听小编慢慢分析。注意:因为这个案列需要用到coolie所以必须在集成环境下运行。

首先,先说说列表页,列表页展示了每件商品的基本信息,我们可以把商品的信息放在一个数组对象里面,然后用数组对象插进去页面,这样以后需要增加商品就可以直接在数组对象里再加一个对象就行了,

pool.js这个案列只用到这一个函数

function $(id){

return document.getElementById(id)

 

}

列表页代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

 <style>

        * {

            margin: 0;

            padding: 0;

        }

        

        #list {

            width: 900px;

            margin: 30px auto;

        }

        

        #list>li {

            width: 230px;

            list-style: none;

            float: left;

            height: 354px;

            margin-right: 10px;

            margin-bottom: 10px;

        }

        

        #list>li:hover div {

            box-shadow: 2px 2px 2px #ccc;

            border: 1px solid #ccc;

        }

        

        .price {

            font-size: 18px;

            color: #e60012;

            font-weight: bold;

            font-family: "Century Gothic";

            line-height: 18px;

            padding: 0 5px;

            margin-bottom: 5px;

        }

        

        .mainTitle {

            line-height: 18px;

            font-size: 12px;

            padding: 0 5px;

        }

        

        .btn {

            width: 90px;

            height: 26px;

            color: #fff;

            text-align: center;

            line-height: 26px;

            background: #ff5c4d;

            display: block;

            text-decoration: none;

            margin-top: 10px;

            margin-left: 135px;

            margin-bottom: 10px;

        }

        #car{width:80px;height: 40px;color: #fff;font-size: 16px;text-align: center;line-height: 40px;text-decoration: none;position: absolute;left:0;top:0;background: red}

    </style>

</head>

<body>

<ul id="list">

        <!--<li>

            <div class="box">

                <img src="img/1.jpg">

                <p class="pirce">230</p>

                <p class="mainTitle">今华方 五得利晶爽饺子王 5kg 麦芯粉半透明面粉 水饺馄饨面条专用粉 10斤 免邮</p>

                <a href="##" class="btn">加入购物车</a>

            </div>

        </li>-->

    </ul>

   <!--  <a href="cart.html" id="car">查看购物车</a> -->

</body>

</html>

<script src="pool.js"></script>

<script>

var obj = [

{

        "id": "01",

        "title": "今华方 五得利晶爽饺子王 5kg 麦芯粉半透明面粉 水饺馄饨面条专用粉 10斤 免邮",

        "price": "230",

        "img": "img/1.jpg"

    }, {

        "id": "02",

        "title": "【泰安馆】山东富世康麦芯挂面面条手擀鸡蛋挂面 多规格 细中粗可选 500g*3",

        "price": "360",

        "img": "img/2.jpg"

    }, {

        "id": "03",

        "title": "伊都拉面棍棍面500g*5包鲜拉面湿面半干面拌面炒面油泼面水煮速食拉面挂面 ",

        "price": "110",

        "img": "img/3.jpg"

    }, {

        "id": "04",

        "title": "仙力面业 2kg刀削面宽面油泼面凉面农家手工筋道整箱挂面面条包邮4",

        "price": "666",

        "img": "img/4.jpg"

    }, {

        "id": "05",

        "title": "贝因美(Beingmate) 全能优+面条 果蔬营养面条260克果蔬营养面条260",

        "price": "530",

        "img": "img/5.jpg"

    }, {

        "id": "06",

        "title": "重庆特产美食小吃正宗麻辣小面重庆小面方便面175gx5速食调料面条DF",

        "price": "99",

        "img": "img/6.jpg"

    }];

 

    var str = '';

    for(var i=0;i<obj.length;i++){

        str+='<li data-id='+obj[i].id+'><div class="box"><img src='+obj[i].img+'><p class="pirce">'+obj[i].price+'</p><p class="mainTitle">'+obj[i].title+'</p><a href="##" class="btn">查看详情</a></div></li>'

    }

    $("list").innerHTML=str

    $("list").onclick=function(e){

        var e = e||event;

        var target = e.target||e.srcElement;

//当点击商品的时候获取商品的自定义属性 得到点击的商品ID

        if(target.tagName=="A"||target.tagName=="P"||target.tagName=="IMG"){

            var id = target.parentNode.parentNode.getAttribute("data-id")   

        }

//点击之后跳转到详情页  ?后面浏览器不会解析 这是为了在详情页得到商品ID做准备

        location.href = "details.html?id="+id

    }

 

</script>

 

效果图如下:

 

 

接下来就到了详情页了,详情页就是用户点击了哪个商品,我们就应该把对应的详细信息展示给用户,那么问题来了,我们怎么知道用户点了哪个商品楞?

这就需要用到我们在列表写的这行代码了 location.href = "details.html?id="+id;

var  str = (location.href).split("?")[1].split("=")[1];

这样str就是用户点击的商品id

这个操作就是先获取网页路径再通过“?”分割成数组得到arr= [details.htmlid=用户点击的商品id],再通过切割数组中的arr[1]也就是id=用户点击的商品id,这次通过“=”切割就会得到newArr=[id,用户点击的商品id],这样newArr就是我们想要商品id

这样当点击第二个商品的时候详情页也就会出现第二个商品的信息了

 

 

 

现在我们开始做放大镜效果,我先来分享一下原理,放大镜就是当你鼠标移入图片的时候有一个半透明的黑色小方块跟着你的鼠标移动,你的鼠标移动一下,右边的图会往反方向移动一点,

怎么才能让半透明小盒子跟着鼠标盒子移动楞,我们要算出半透明的小方块的lefttop值、

Left值如下图,top值同理

 

 

 

  Top值和left值都获取到了 半透明小盒子就可以跟着鼠标移动了,加减操作就是点击按钮让下一个节点innerHTML--或者上一个节点++而已

加入购物车操作我们需要判断以前用户购物车里有没有商品 没有则之接创建一个cookie把商品信息存入cookie中,如果有,则先把cookie中的数据拿出来 和当前要加入的商品的id进行对比,如果id相同则只进行数量上的相加,如果不同则,新建一个对象,合并成一个数组对象存进cookie中,具体代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

    <link rel="stylesheet" type="text/css" href="reset.css">

<style>

            img{display: block;}

        #box{width: 1000px;margin: 100px auto;border:1px #ccc solid;}

        .box-l{width: 400px;position: relative;}

        .box-l img{width: 100%}

        .box-r{width: 500px}

        #box p {padding: 60px 0;margin-left: 20px;font-size: 30px}

        h2{margin-top:10px ;margin-left: 20px}

         .btn {

            margin-left: 20px;

            width: 120px;

            height: 40px;

            color: #fff;

            text-align: center;

            line-height: 40px;

            background: #ff5c4d;

            display: block;

            text-decoration: none;

        }

        a{cursor: pointer;}

        #small{width: 200px;height: 200px;background: #000;opacity: 0.5;position: absolute;top:0;left: 0;display: none;cursor: move}

        #max{width: 400px;height: 400px;position: absolute;left: 420px;top:0;overflow: hidden;display: none}

        #maxImg{width: 800px;height: 800px;position: absolute;}

        #shuliang{margin: 30px 0 60px 20px}

        #shuliang a{padding: 2px 8px;border:1px #ccc solid;}

        #shuliang span{padding: 2px 10px;border:1px #ccc solid;}

        .car{width:80px;height: 40px;color: #fff;font-size: 16px;text-align: center;line-height: 40px;text-decoration: none;position: absolute;left:0;top:0;background: red}

        .car1{top:50px}

    </style>

</head>

<body>

<a href="list.html" class="car">首页</a>

<a href="cart.html" class="car car1">查看购物车</a>

  <div id="box" class="clearfix ">

<!--

                <div class="fl box-l" id="box-l">

                    <img src="img/1.jpg">

                    <div id="small"></div>

                    <div id="max"><img src="img/1.jpg" id="maxImg"></div>

                </div>

                <div class="fl box-r">

                    <h2 class="mainTitle">今华方 五得利晶爽饺子王 5kg 麦芯粉半透明面粉     水饺馄饨面条专用粉 10斤 免邮</h2>

                    <p class="pirce">230</p>

                    <div id="shuliang"><a href="" id="jian">-</a><span>1</span><a href="#" id="jia">+</a></div>

                    <a href="##" class="btn">加入购物车</a>

                   </div> -->

            </div>

</body>

</html>

<script src="pool.js"></script>

<script>

var obj = [

{

        "id": "01",

        "title": "今华方 五得利晶爽饺子王 5kg 麦芯粉半透明面粉 水饺馄饨面条专用粉 10斤 免邮",

        "price": "230",

        "img": "img/1.jpg"

    }, {

        "id": "02",

        "title": "【泰安馆】山东富世康麦芯挂面面条手擀鸡蛋挂面 多规格 细中粗可选 500g*3",

        "price": "360",

        "img": "img/2.jpg"

    }, {

        "id": "03",

        "title": "伊都拉面棍棍面500g*5包鲜拉面湿面半干面拌面炒面油泼面水煮速食拉面挂面 ",

        "price": "110",

        "img": "img/3.jpg"

    }, {

        "id": "04",

        "title": "仙力面业 2kg刀削面宽面油泼面凉面农家手工筋道整箱挂面面条包邮4",

        "price": "666",

        "img": "img/4.jpg"

    }, {

        "id": "05",

        "title": "贝因美(Beingmate) 全能优+面条 果蔬营养面条260克果蔬营养面条260",

        "price": "530",

        "img": "img/5.jpg"

    }, {

        "id": "06",

        "title": "重庆特产美食小吃正宗麻辣小面重庆小面方便面175gx5速食调料面条DF",

        "price": "99",

        "img": "img/6.jpg"

    }];

    //通过路径获取这个页面的id

    var  str = (location.href).split("?")[1].split("=")[1];

    //通过for循环和if判断  获取这个id的相关内容 插入页面中

    for(var i=0;i<obj.length;i++){

        if(str==obj[i].id){

            var str1 = '<div class="fl box-l" id="box-l" data-id='+obj[i].id+'><img src='+obj[i].img+'><div id="small"></div><div id="max"><img src='+obj[i].img+' id="maxImg"></div></div><div class="fl box-r"><h2 class="mainTitle">'+obj[i].title+'</h2><p class="pirce">'+obj[i].price+'</p><div id="shuliang"><a id="jian">-</a><span>1</span><a id="jia">+</a></div><a href="#" class="btn">加入购物车</a></div>'

        }

    }

    $("box").innerHTML=str1

    //放大镜效果

    $("box-l").onmouseover=function(){

        $("small").style.display="block";

        $("max").style.display="block";

        this.onmousemove=function(e){

            var e=e||event;

            var l = e.clientX-this.offsetLeft-$("small").offsetWidth/2;

            var t = e.clientY-this.offsetTop-$("small").offsetHeight/2;

            l = l>this.offsetWidth-$("small").offsetWidth?this.offsetWidth-$("small").offsetWidth:(l<0?0:l);

            t = t>this.offsetHeight-$("small").offsetHeight?this.offsetHeight-$("small").offsetHeight:(t<0?0:t)

            $("small").style.left=l+"px";

            $("small").style.top=t+"px";

            $("maxImg").style.left=-2*l+"px";

            $("maxImg").style.top=-2*t+"px";

        }

    }

      $("box-l").onmouseout=function(){

        $("small").style.display="none";

        $("max").style.display="none"

    }

    

    var oNum = {};

    var arr = [];

    $("box").onclick=function(e){

        var e = e||event;

        var target=e.target||e.srcElemengt;

        //防止点击a标签自动在链接后面加#刷新变成undefined

        e.preventDefault?e.preventDefault():e.returnValue = false;

        //加减操作

        if(target.id=="jia"){

            target.previousElementSibling.innerHTML++

        }

        if(target.id=="jian"){

            if(target.nextElementSibling.innerHTML>1){

                target.nextElementSibling.innerHTML--

            }

        }

        //点击加入购物车

        if(target.className=="btn"){

            //获取要加入购物车商品的数量

            var count = Number(target.previousElementSibling.children[1].innerHTML);

            //判断cookie里有没有数据 如果没有则直接插入 如果有再判断现在要加入的商品cookie里有没有同样的商品

            if(getCookie("intel")){

                var cookieJson = JSON.parse(getCookie("intel"));

                var bStop = false;

                for(var i=0;i<cookieJson.length;i++){

                //现在要加入的商品cookie里已经存在 所以只需要进行数量上的相加

                    if(cookieJson[i].id == str){

                        cookieJson[i].num+=count;

                        bStop = true;

                        break;

                    }

                }

                //现在要加入的商品cookie里没有 所以把这条数据插进去再存入cookie

                if(!bStop){

                    oNum = {id:str,num:count}

                    cookieJson.push(oNum);

                }

                setCookie("intel",JSON.stringify(cookieJson))

            }else{

                //cookie里没有数据 所以直接插入就行

                oNum = {id:str,num:count}

                arr.push(oNum);

                setCookie("intel",JSON.stringify(arr))

            }  

        }  

    }

 

</script>

 

效果图:

 

当点击第一商品5件  第二件商品10  我们看看cookie中存入的数据

 

 

存入的数据没毛病 这时候点击查看购物车 我们只需要把这数据拿出来 插入页面就行了

购物车的全选发选:当全选的checkboxtrue时,用for循环遍历让下面的checkbox都为true;反之当全选的checkboxfalse时,用for循环遍历让下面的checkbox都为false

当下面的选择都勾上的时候,全选自动勾上,又是怎么实现的楞

for(var i=0;i<xuanze.length;i++){

                xuanze[i].onclick = function(){

                    var bStop = true;   

                    for(var j=0;j<xuanze.length;j++){

                        if(!xuanze[j].checked){

                            bStop = false;

                            break;

                        }

                    }

                    $("quanxuan").checked = bStop;

                }

        }

只要有一个选择为false ;bStop就会flase;

加减详情页就做过了,也就是点击上上一个或者下一个节点的innerHTML-- ++;

删除操作就是点击删除他的父级;

具体代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

        #list {

            width: 800px;

            text-align: center;

            border-spacing: 0;

            table-layout: fixed;

            margin: 30px auto;

        }

        

        #list>tbody>tr {

            border: 1px solid #ccc;

            background: #f3b8b8;

            height: 87px;

        }

        

        #list>tbody>tr>td {

            margin-left: 30px;

            width: 20%;

        }

        #list>tbody>tr>td>img{

          

        }

        

        #list>tbody>tr>td>button {

            height: 22px;

            width: 30px;

            font-size: 18px;

            outline: none;

        }

        

        #list>tbody>tr>td>button,

        #list>tbody>tr>td>input {

            border: 0;

            float: left;

        }

        

        .reduce {

            margin-left: 30px;

        }

        

        .num {

            text-align: center;

        }

        

        #list>tbody>tr>td>input {

            width: 40px;

            height: 20px;

        }

        

        .smallPic {

            width: 60px;

            height: 60px;

        }

        #car{width:80px;height: 40px;color: #fff;font-size: 16px;text-align: center;line-height: 40px;text-decoration: none;position: absolute;left:0;top:0;background: red}

        button,.del{cursor: pointer;}

    </style>

</head>

<body>

<a href="list.html" id="car">首页</a>

<table id="list">

        <tr>

            <td><input type="checkbox" id="quanxuan"/><label for="quanxuan">全选</label></td>

            <td>图片</td>

            <td>单价</td>

            <td>数量</td>

            <td>小计</td>

            <td>操作</td>

        </tr>

        <!-- <tr>

        <td><input type="checkbox"/></td>

            <td><img src="img/1.jpg" class="smallPic"></td>

            <td>255</td>

            <td>

                <button class="reduce">-</button>

                <input type="text" value="1" class="num">

                <button class="add">+</button>

            </td>

            <td>255</td>

            <td class="del">删除</td>

        </tr> -->

 

    </table>

</body>

</html>

<script src="pool.js"></script>

<script>

var obj = [

{

        "id": "01",

        "title": "今华方 五得利晶爽饺子王 5kg 麦芯粉半透明面粉 水饺馄饨面条专用粉 10斤 免邮",

        "price": "230",

        "img": "img/1.jpg"

    }, {

        "id": "02",

        "title": "【泰安馆】山东富世康麦芯挂面面条手擀鸡蛋挂面 多规格 细中粗可选 500g*3",

        "price": "360",

        "img": "img/2.jpg"

    }, {

        "id": "03",

        "title": "伊都拉面棍棍面500g*5包鲜拉面湿面半干面拌面炒面油泼面水煮速食拉面挂面 ",

        "price": "110",

        "img": "img/3.jpg"

    }, {

        "id": "04",

        "title": "仙力面业 2kg刀削面宽面油泼面凉面农家手工筋道整箱挂面面条包邮4",

        "price": "666",

        "img": "img/4.jpg"

    }, {

        "id": "05",

        "title": "贝因美(Beingmate) 全能优+面条 果蔬营养面条260克果蔬营养面条260",

        "price": "530",

        "img": "img/5.jpg"

    }, {

        "id": "06",

        "title": "重庆特产美食小吃正宗麻辣小面重庆小面方便面175gx5速食调料面条DF",

        "price": "99",

        "img": "img/6.jpg"

    }];

   var oList = document.getElementById("list");

   var str = "";

//如果cookie里面有这个属性的话

    if(getCookie("intel")){

     //如果数据存在那么将字符串转换为json

     var data = JSON.parse(getCookie("intel"));

        console.log(data)

     for(var i in data){

            

     for(var j in obj){

                //匹配id插入内容

     if(data[i].id == obj[j].id){

     str+='<tr><td><input type="checkbox" class="xuanze"/></td><td><img src='+obj[j].img+' class="smallPic"></td><td>'+obj[j].price+'</td><td><button id="jian">-</button><input type="text" value='+data[i].num+' class="num"><button id="jia">+</button></td><td>'+(obj[j].price.slice(1)*data[i].num)+'</td><td class="del">删除</td></tr>'

     }

     }

     }

     oList.innerHTML += str;

    }

    oList.onclick=function(e){

        var e=e||event;

        var target = e.target||e.srcElement;

        if(target.className=="del"){

            target.parentNode.remove()

        }

         if(target.id=="jia"){

            target.previousElementSibling.value++;

            var shulian = target.previousElementSibling.value;

            var jiage = target.parentNode.previousElementSibling.innerHTML.slice(1);

            target.parentNode.nextElementSibling.innerHTML = ""+shulian*jiage

        }

        if(target.id=="jian"){

            if(target.nextElementSibling.value>1){

                target.nextElementSibling.value--;

                var shulian = target.nextElementSibling.value;

                var jiage = target.parentNode.previousElementSibling.innerHTML.slice(1);

                target.parentNode.nextElementSibling.innerHTML = ""+shulian*jiage

            }

        }

         var xuanze = oList.getElementsByClassName("xuanze")

        if(target.id == "quanxuan"){

           

            if(target.checked){

                for(var i=0;i<xuanze.length;i++){

                    xuanze[i].checked = true

                }

            }else{

                for(var i=0;i<xuanze.length;i++){

                    xuanze[i].checked = false

                }

            }

            

        }

        for(var i=0;i<xuanze.length;i++){

                xuanze[i].onclick = function(){

                    var bStop = true;   

                    for(var j=0;j<xuanze.length;j++){

                        if(!xuanze[j].checked){

                            bStop = false;

                            break;

                        }

                    }

                    $("quanxuan").checked = bStop;

                }

        }

    }

</script>

效果图:

 

 

我们在去首页添加第三种商品试试,不买多了就买个15件好了

 

 

再测试一下加减全选和删除  我们第一件商品删了 ,第二件商品加2 第三件商品减2 然后再全选

 

没毛病,这样简单的购物车就做好了。

posted @ 2018-05-21 00:49  刘雄辉  阅读(624)  评论(1编辑  收藏  举报