购物车数字加减
效果图
html
<ul class="btn-numbox"> <li> <ul class="count"> <li style="margin-left: 40px;"><span id="num-jian" class="num-jian">-</span></li> <li><input type="text" class="input-num" id="input-num" value="0"></li> <li><span id="num-jia" class="num-jia">+</span></li> </ul> </li> </ul>
css
* {padding: 0;margin: 0;border: 0;outline: 0} ul,li {list-style: none;} a {text-decoration: none;} a:hover {cursor: pointer;text-decoration: none;} a:link {text-decoration: none;} img {vertical-align: middle;} .btn-numbox {overflow: hidden;margin-top: 20px;margin-left: 40px;} .btn-numbox li {float: left;} .btn-numbox li .number,.kucun { display: inline-block; font-size: 12px; color: #808080; vertical-align: sub; } .btn-numbox .count { overflow: hidden; margin: 0 16px 0 -20px; } .btn-numbox .count .num-jian, .input-num, .num-jia { display: inline-block; width: 28px; height: 28px; line-height: 28px; text-align: center; font-size: 18px; color: #999; cursor: pointer; border: 1px solid #e6e6e6; } .btn-numbox .count .input-num { width: 58px; height: 28px; color: #333; border-left: 0; border-right: 0; }
js
jquery实现 $('.num-jian').click(function(e) { //closest() 获得匹配选择器的第一个祖先元素 console.log($(this).find('.input-num')); var obj = $(this).closest('ul').find('.input-num'); if (obj.val() <= 0) { obj.val(0); } else { obj.val(parseInt(obj.val()) - 1); } obj.change(); }); $('.num-jia').click(function(m) { var obj = $(this).closest('ul').find('.input-num'); obj.val(parseInt(obj.val()) + 1); obj.change(); }); 原生js实现 var num_jia = document.getElementById('num-jia'); var num_jian = document.getElementById('num-jian'); var input_num = document.getElementById('input-num'); num_jia.onclick = function() { input_num.value = parseInt(input_num.value) + 1; } num_jian.onclick = function() { if(input_num <= 0) { input_num.value = 0; } else { input_num.value = parseInt(input_num.value) - 1; } }