<style>
.num-input {
height: 30px;
}
.num-input button {
width: 22px;
height: 100%;
}
.num-input input {
width: 35px;
height: 100%;
text-align: center;
}
// 去除input number类型时自带的上下箭头
.num-input input::-webkit-outer-spin-button,
.num-input input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.num-input input[type="number"] {
-moz-appearance: textfield;
}
</style>
<div class="num-input">
<button id="subVal">-</button>
<input id="number" type="number" value="1" >
<button id="addVal">+</button>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// 给input框声明一个变量
var n = $('#number')
// 减
$('#subVal').click(function() {
// parseInt() 转化为数字类型
console.log(parseInt(n.val()))
if(parseInt(n.val()) < 1) {
// 小于1时 默认恢复为1
n.val(1)
} else if(parseInt(n.val()) > 1) {
// 大于1时 点击减1
n.val(parseInt(n.val())-1)
} else {
// 小于1时 给减按钮添加一个禁止点击的状态
$('#subVal').attr('disabled','disabled')
}
})
// 加
$('#addVal').click(function() {
if(parseInt(n.val()) < 1) {
// 小于1时 默认恢复为1
n.val(1)
} else {
// 大于1时 点击加1
n.val(parseInt(n.val())+1)
// 大于1时 解除减按钮禁止点击的状态
$('#subVal').removeAttr('disabled')
}
console.log(parseInt(n.val()))
})
</script>
参考:https://blog.csdn.net/qq_42354773/article/details/80974852