js简易版购物车功能
程序员文章站
2022-03-21 14:58:43
本文实例为大家分享了js购物车功能的具体代码,供大家参考,具体内容如下
<...
本文实例为大家分享了js购物车功能的具体代码,供大家参考,具体内容如下
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <style> * { margin: 0; padding: 0; } li { list-style: none; } li { float: left; width: 200px; border: 1px #000 solid; margin: 10px; } li img { width: 200px; } p { height: 20px; border-bottom: 1px #333 dashed; } #bus { width: 600px; border: 1px #000 solid; height: 300px; clear: both; } .box1 { float: left; width: 200px; } .box2 { float: left; width: 200px; } .box3 { float: left; width: 200px; } #allmoney { float: right; } </style> <script> window.onload = function() { var olist = document.getelementbyid('list'); var ali = olist.getelementsbytagname('li'); var obus = document.getelementbyid('bus'); var obj = {}; var inum = 0; var allmoney = 0; for (var i = 0; i < ali.length; i++) { ali[i].ondragstart = function(ev) { //点击拖拽元素的时候,就设置数据,以后放到购物车的时候数据就可以传过去了 var ev = ev || window.event; var ap = this.getelementsbytagname('p'); ev.datatransfer.setdata('title', ap[0].innerhtml); ev.datatransfer.setdata('price', ap[1].innerhtml); ev.datatransfer.setdragimage(this, 0, 0); } } obus.ondragover = function(ev) { //阻止鼠标默认事件 var ev = ev || event; ev.preventdefault(); }; obus.ondrop = function(ev) { var ev = ev || event; var title = ev.datatransfer.getdata('title'); var price = ev.datatransfer.getdata('price'); if(!obj[title]){ var op = document.createelement('p'); var ospan = document.createelement('span'); ospan.classname = 'box1'; ospan.innerhtml = 1; op.appendchild(ospan); var ospan = document.createelement('span'); ospan.classname = 'box2'; ospan.innerhtml = title; op.appendchild(ospan); var ospan = document.createelement('span'); ospan.classname = 'box3'; ospan.innerhtml = price; op.appendchild(ospan); obus.appendchild(op); obj[title] = 1; }else{ var box1 = document.getelementsbyclassname('box1'); var box2 = document.getelementsbyclassname('box2'); for(var i=0;i<box2.length;i++){ if(box2[i].innerhtml == title){ box1[i].innerhtml = parseint(box1[i].innerhtml) + 1; }; }; }; //总价 if(!allmoney){ allmoney = document.createelement('div'); allmoney.id = 'allmoney'; } inum += parseint(price); allmoney.innerhtml = '¥'+inum; obus.appendchild(allmoney); }; }; </script> </head> <body> <ul id="list"> <li draggable="true"> <img src="img/img1.jpg" /> <p>javascript语言精粹</p> <p>40¥</p> </li> <li draggable="true"> <img src="img/img2.jpg" /> <p>javascript权威指南</p> <p>120¥</p> </li> <li draggable="true"> <img src="img/img3.jpg" /> <p>精通javascript</p> <p>35¥</p> </li> <li draggable="true"> <img src="img/img4.jpg" /> <p>dom编程艺术</p> <p>45¥</p> </ul> <div id="bus"></div> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: jQuery实现下拉菜单的实例代码
下一篇: jQuery实现简单的手风琴效果