先看效果
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="这里引入自己的iconfont图标地址">
<style>
.quantity-control {
display: flex;
align-items: center;
background-color: #f5f6fa;
border-radius: 0.3rem;
overflow: hidden;
}
.quantity-btn {
text-align: center;
background-color: #f5f6fa;
border: none;
border-width: 0;
width: 32px;
height: 32px;
line-height: 32px;
vertical-align: middle;
}
.quantity-btn i {
font-size: 14px !important;
color: #505259;
}
.quantity-input {
border-width: 0;
width: 46px;
text-align: center;
margin: 0;
color: #505259;
border: none;
outline: none;
background-color: transparent;
}
.disabled {
cursor: not-allowed;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
</head>
<body>
<div style="display: flex;">
<div class="quantity-control">
<button class="quantity-btn minus" id="minus">
<i class="iconfont icon-jian"></i>
</button>
<input type="text" id="numberInput" class="quantity-input" value="1" min="1" max="10">
<button class="quantity-btn plus" id="plus">
<i class="iconfont icon-jia"></i>
</button>
</div>
</div>
<script>
$(document).ready(function () {
let minValue = $("#numberInput").attr("min") || 1;
let maxValue = $("#numberInput").attr("max") || 100;
let currentValue = $("#numberInput").val();
setOperatorButtonState(minValue, maxValue, currentValue, '#numberInput', '#plus', '#minus');
// 监听input输入变化
$('#numberInput').on('input', function () {
let value = $(this).val();
// 只允许数字输入
value = value.replace(/[^\d]/g, '');
$(this).val(value);
if (value === '') {
value = 1;
}
let numValue = parseInt(value);
// 限制最小值和最大值
if (numValue < minValue) numValue = minValue;
if (numValue > maxValue) numValue = maxValue;
$(this).val(numValue);
setOperatorButtonState(minValue, maxValue, numValue, '#numberInput', '#plus', '#minus');
});
$('.plus').click(function () {
var input = $(this).siblings('.quantity-input');
var value = parseInt(input.val());
var newValue = value + 1;
setOperatorButtonState(minValue, maxValue, newValue, '#numberInput', '#plus', '#minus');
});
$('.minus').click(function () {
var input = $(this).siblings('.quantity-input');
var value = parseInt(input.val());
var newValue = value - 1;
setOperatorButtonState(minValue, maxValue, newValue, '#numberInput', '#plus', '#minus');
});
});
function setOperatorButtonState(minValue, maxValue, currentValue, numberInputId, plusId, minusId) {
if (currentValue >= maxValue) {
$(plusId).prop('disabled', true);
$(plusId).addClass('disabled');
currentValue = maxValue;
} else {
$(plusId).prop('disabled', false);
$(plusId).removeClass('disabled');
}
if (currentValue <= minValue) {
$(minusId).prop('disabled', true);
$(minusId).addClass('disabled');
currentValue = minValue;
} else {
$(minusId).prop('disabled', false);
$(minusId).removeClass('disabled');
}
$(numberInputId).val(currentValue);
}
</script>
</body>
</html>