自己的第一个jquery插件,规模虽然不大,但是小成就满满,对jquery又有了更进一步的认识。
简单实用的数字加减插件,实现通过加减按钮对文本框内的数字进行增减操作。
效果图:
参数:
默认值、最大值、最小值、增减度。
可单独对每个input设置参数,也可以对所有input统一设置。参考代码在下方:
使用方法:
1.引用CSS、js文件(记得引用jquery.min.js)
2.前台:
2.1无参数
<inputtype="text"class="numberText"/><scripttype="text/javascript">$(".numberText").spinner();</script>
2.2整体参数
<inputtype="text"class="numberText"/><scripttype="text/Javascript">$(".numberText").spinner({
value:1,
min: 0,
max:15,
step: 1});</script>
2.3逐个设置参数
<inputtype="text"class="numberText"value="11"data-step="1"data-min="0"data-max="10"/><inputtype="text"class="numberText"value="11"data-step="1"data-min="0"/><inputtype="text"class="numberText"/><scripttype="text/javascript">$(".numberText").spinner({
value:5,
min:-2,
max:15,
step:2});</script>
3.CSS
span.spin-text{display:inline-block;overflow:hidden;border:1px solid silver;
}span.spin-text .spin-val{border:1px solid silver;border-top:none;border-bottom:none;vertical-align:middle;width:30px;height:18px;text-align:center;
}span.spin-text a{display:inline-block;width:20px;height:20px;line-height:20px;border:none;text-align:center;vertical-align:middle;text-decoration:none;background:#fff;font-family:宋体;font-weight:bold;font-size:14px;
}span.spin-text a:hover{background:#f3f3f3;
}
4.JS
/*jQuery加减数字插件
作者:metro-liang
时间:2015-10-16
版本:v1.0*//*参数:value:默认值
min:允许的最小值
max:允许的最大值
step:增减度*/; (function($) {
$.fn.extend({
spinner:function(options) {returnthis.each(function() {vardefaults ={
value:1,
min:1,
max:100,
step:1};var_this = $(this);varopts =$.extend(defaults, options);
opts.step= _this.data("step") !=null? _this.data("step") : opts.step;
opts.min= _this.data("min")!=null? _this.data("min"):opts.min;
opts.max= _this.data("max") !=null? _this.data("max") : opts.max;
opts.value= _this.val() != "" ?_this.val() : opts.value;if(opts.value > opts.max || opts.value <opts.min) {
opts.value=opts.max;
}varcontainer = $('<span></span>').addClass('spin-text');vartextField = _this.addClass('spin-val').val(opts.value).css("ime-mode","Disabled").keyPRess(function() {return(/[\d]/.test(String.fromCharCode(event.keyCode)));
}).bind("copy cut paste",function(e){returnfalse;
});vardecreaseBtn = $('<a href="javascript:void(0)">-</a>').click(function() { changeValue(-1) });varincreaseBtn = $('<a href="javascript:void(0)">+</a>').click(function() { changeValue(1) });
textField.before(decreaseBtn).after(increaseBtn);
textField.add(increaseBtn).add(decreaseBtn).wrapAll(container);functionchangeValue(d) {varvalue =parseInt(textField.val());if(isNaN(value))
{
value=opts.min;
}var_val = value + d *opts.step;if(_val <= opts.max && _val >=opts.min) {
value=_val;
}
textField.val(value);
}
});
}
});
})(jQuery);