<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>数字输入框</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.number-group{
display: inline-block;
overflow: hidden;
border: 1px solid #ddd;
border-radius: 4px;
margin-top: 50px;
margin-left: 50px;
color: #333;
}
.number-group:hover{
border-color: #409eff;
}
.number-group [type="text"]{
width: 50px;
height: 30px;
outline: none;
border:none;
float: left;
text-align: center;
}
.number-group a{
width: 30px;
height: 30px;
float: left;
text-align: center;
line-height: 30px;
font-size: 18px;
user-select: none;
cursor: pointer;
}
.number-group a.disable{
cursor: not-allowed;
opacity: .5;
}
.number-group a:first-of-type{
border-right:1px solid #ddd;
font-size: 24px;
}
.number-group a:last-of-type{
border-left:1px solid #ddd;
}
.number-group .native{
display: none;
}
</style>
<body>
<input type="number">
<input type="number">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script>
$(function(){
my_group(1,12);
function my_group(min=1,max=10){
//组装
$('[type="number"]').wrap(function(){
return `<div class="number-group">
<span class="native"></span>
<a class="disable">-</a>
<input type="text" value="${min}">
<a>+</a>
</div>`;
});
//绑定事件
//自己的输入框
var $myinput = $('.number-group [type="text"]');
//减
$myinput.prev().click(function(){
var $parent = $(this).closest('.number-group');
var value = $parent.find('[type="text"]').val()-1;
$(this).siblings('a').removeClass('disable')
if(value <= min){
value = min;
$(this).addClass('disable');
}
$parent.find('input').val(value);
})
//加
$myinput.next().click(function(){
var $parent = $(this).closest('.number-group');
var value = Number($parent.find('[type="text"]').val())+1;
$(this).siblings('a').removeClass('disable')
if(value >= max){
value = max;
$(this).addClass('disable');
}
$parent.find('input').val(value);
})
//直接输入(不能输入非数字)
$myinput.on('input',function(){
var value = $(this).val().replace(/\D/g,'');
$(this).val(value);
})
//用户确认后
$myinput.change(function(){
var value = $(this).val();
$(this).siblings('a').removeClass('disable')
if( value<=min ){
value = min;
//减按钮失效
$(this).prev().addClass('disable');
}
if(value >= max){
value = max
//加按钮失效
$(this).next().addClass('disable');
}
$(this).val(value);
})
}
})
</script>
</body>
</html>
jq版数字按钮输入框
最新推荐文章于 2022-04-20 23:30:06 发布