小巧实用的数字加减插件(jquery插件)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

自己的第一个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);

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航