jquery实现点击数量增加总价跟着增加且数量有上限下限
效果图:
整体代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>count</title>
<style>
.show{
display: none;
width: 250px;
height: 50px;
background-color: #009688;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
text-align: center;
line-height: 15px;
}
</style>
</head>
<body>
<div class="show">
</div>
<ul>
<li>单价:<span class="s_price">10.1</span></li>
<li>总价:<span class="t_price"></span></li>
<li>数量:<span class="sub">-</span><input id="count" type="text" value="0" /><span class="add">+</span></li>
</ul>
<script type="text/javascript" src="js/jquery-3.3.1.js" ></script>
<script>
$(function(){
//获取数量
var num = $('#count').val();
//获取单价
var unitPrice = $('.s_price').text();
//计算总价
function count(){
$('.t_price').text((num*unitPrice).toFixed(2));
}
//点击加或者减的时候,实现加减的操作
//点击减
$('.sub').click(function(){
num--;
if(num<1){
$(".show").show().html("数量不能小于1").delay(600).hide(500);
}
$('#count').val(num);
count();
})
//点击加
$('.add').click(function(){
num++;
if(num>5){
$(".show").show().html("数量不能大于5").delay(600).hide(500);
}
$('#count').val(num);
count();
})
//键盘事件
$('#count').keyup(function(){
num = $(this).val();
var res = /^[1-9]\d*$/
if(res.test(num)){
count();
} else{
$(this).val(1);
$(".show").show().html("输入不合法").delay(1000).hide(500);
count();
}
})
})
</script>
</body>
</html>