第一步先布局好html格式
<body>
<div class="div1">
<ul>
<li draggable="true">
<img src="img/1.jpg" />
<p>爱马仕kelly手提包</p>
<p>¥78000</p>
</li>
<li draggable="true">
<img src="img/2.jpg" />
<p>爱马仕鳄鱼kelly包</p>
<p>¥180000</p>
</li>
<li draggable="true">
<img src="img/3.jpg" />
<p>卡地亚钉子手镯</p>
<p>¥50000</p>
</li>
<li draggable="true">
<img src="img/4.jpg" />
<p>波斯猫</p>
<p>¥5200</p>
</li>
<li draggable="true">
<img src="img/5.jpg" <p>法拉利红色跑车</p>
<p>¥1200000</p>
</li>
<li draggable="true">
<img src="img/6.jpg" />
<p>保时捷敞篷车</p>
<p>¥100000</p>
</li>
</ul>
</div>
<div class="div2">
<p>
<span class="box1">数量</span>
<span class="box2">商品名称</span>
<span class="box3">单价</span>
</p>
</div>
第二步再完成css样式
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
float: left;
width: 200px;
border: 1px #000 solid;
margin: 30px;
}
li img {
height: 260px;
width: 200px;
}
p {
height: 20px;
border-bottom: 1px #333 dashed;
}
.div1 {
height: 360px;
border: 1px gray solid;
margin: 130px auto;
position: relative;
overflow: hidden;
}
.div2 {
border: 1px #000 solid;
height: 300px;
margin-top: 120px;
clear: both;
}
.box1 {
float: left;
width: 200px;
text-align: center;
}
.box2 {
float: left;
width: 200px;
text-align: center;
}
.box3 {
float: left;
width: 200px;
text-align: center;
}
.allMoney {
float: right;
}
</style>
第三步是使用js代码以实现功能
<script>
window.onload = function() {
var aLi = document.getElementsByTagName('li');
var oDiv = document.getElementsByClassName('div2')[0];
var obj = {};
var iNum = 0;
var allMoney = null;
for(var i = 0; i < aLi.length; i++) {
aLi[i].ondragstart = function(ev) {
var aP = this.getElementsByTagName('p');
ev.dataTransfer.setData('title', aP[0].innerHTML);
ev.dataTransfer.setData('money', aP[1].innerHTML);
ev.dataTransfer.setDragImage(this, 0, 0);
};
oDiv.ondragover = function(ev) {
ev.preventDefault();
}
oDiv.ondrop = function(ev) {
ev.preventDefault();
var Ltitle = ev.dataTransfer.getData('title');
var Lmoney = ev.dataTransfer.getData('money');
if(!obj[Ltitle]) {
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 = Ltitle;
oP.appendChild(oSpan);
var oSpan = document.createElement('span');
oSpan.className = 'box3';
oSpan.innerHTML = Lmoney;
oP.appendChild(oSpan);
oDiv.appendChild(oP);
obj[Ltitle] = 1;
} else {
var aBox1 = document.getElementsByClassName('box1');
var aBox2 = document.getElementsByClassName('box2');
for(var i = 0; i < aBox2.length; i++) {
if(aBox2[i].innerHTML == Ltitle) {
aBox1[i].innerHTML = parseInt(aBox1[i].innerHTML) + 1;
}
}
}
if(!allMoney) {
allMoney = document.createElement('div');
allMoney.className = 'allMoney';
}
iNum += parseInt(Lmoney);
allMoney.innerHTML = '合计:' + iNum + '¥';
oDiv.appendChild(allMoney);
}
}
}
</script>