实现效果:
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.fruit-list{
/* 让div位于同一行 */
display: flex;
/* 挤不下换行 */
flex-wrap: wrap;
/* 居中 */
justify-content: center;
}
.fruit{
width: 200px;
text-align: center;
}
.footer{
text-align: center;
}
</style>
</head>
<body>
<h5 align="center">购物车</h5>
<div class="fruit-list">
<div class="fruit">
<div>
<img src="img1.jpg" width="150px" height="190px" alt="">
<div>橘子 ¥3</div>
<div>
<!-- 传参时在参数前面加上'.' -->
<button onclick="addNumber('.fruit1-num',3)">+</button>
<span class="fruit1-num">0</span>
<button onclick="removeNumber('.fruit1-num',3)">-</button>
</div>
</div>
</div>
<div class="fruit">
<img src="img2.jpg" width="150px" height="190px" alt="">
<div>车厘子 ¥138</div>
<div>
<button onclick="addNumber('.fruit2-num',128)">+</button>
<span class="fruit2-num">0</span>
<button onclick="removeNumber('.fruit2-num',128)">-</button>
</div>
</div>
<div class="fruit">
<img src="img3.jpg" width="150px" height="190px" alt="">
<div>草莓 ¥28</div>
<div>
<button onclick="addNumber('.fruit3-num',28)">+</button>
<span class="fruit3-num">0</span>
<button onclick="removeNumber('.fruit3-num',28)">-</button>
</div>
</div>
<div class="fruit">
<img src="img4.jpg" width="150px" height="190px" alt="">
<div>菠萝 ¥8</div>
<div>
<button onclick="addNumber('.fruit4-num',8)">+</button>
<span class="fruit4-num">0</span>
<button onclick="removeNumber('.fruit4-num',8)">-</button>
</div>
</div>
</div>
<div class="footer">
总价:¥<span class="total-price">0</span>
</div>
<script>
function addNumber(fruitclass,price){
// 获取水果价格标签
let fruitNum=document.querySelector(fruitclass).innerHTML;
fruitNum++;
document.querySelector(fruitclass).innerHTML=fruitNum;
// 获取总价标签
let totalPrice=document.querySelector(".total-price").innerHTML;
document.querySelector(".total-price").innerHTML=totalPrice*1+price*1;
}
function removeNumber(fruitclass,price){
// 获取水果价格标签
let fruitNum=document.querySelector(fruitclass).innerHTML;
fruitNum--;
// 如果水果数量标签小于0,则为0
if(fruitNum<0){
document.querySelector(fruitNum).innerHTML=0;
}else{
document.querySelector(fruitclass).innerHTML=fruitNum;
// 获取总价标签
let totalprice=document.querySelector(".total-price").innerHTML;
document.querySelector(".total-price").innerHTML=totalprice*1-price*1;
}
}
</script>
</body>
</html>