css
.div_1 {
position:absolute;
font-size:9pt;
color:#4586b5;
width:50px;
text-align:right;
display:none;
}
javascript
(function($) {
$.fn.getSelection=function(){
var selection={selectionStart:0,selectionEnd:0
//,selectionText:""
};
var thiz=this.get(0);
if(!(thiz.type=="textarea"||thiz.type=="text")){
return selection;
}
if (thiz.selectionStart) {
selection.selectionStart=thiz.selectionStart;
selection.selectionEnd=thiz.selectionEnd;
//selection.selectionText=this.value.substring(this.selectionStart, this.selectionEnd);
}else{
var range1 = document.selection.createRange();
if (range1.parentElement() != thiz) return;
var range2 = range1.duplicate();
range2.moveToElementText(thiz);
range2.setEndPoint('EndToEnd', range1);
selection.selectionStart=range2.text.length - range1.text.length;
selection.selectionEnd=selection.selectionStart + range1.text.length;
//selection.selectionText=range1.text;
}
return selection;
};
})(jQuery);
(function($) {
$.fn.inputlimiter = function(options) {
var settings = {
maxLength : 200,
tipDiv : '<div style="display:none;" class="div_1">0/200</div>'
};
var options = $.extend(settings, options);
var $show =$(options.tipDiv).insertAfter(this);
this.bind("focus keyup input paste", function() {
var $thiz=$(this);
var _length = $thiz.val().length;
if (_length > options.maxLength) {
$thiz.val($thiz.val().substring(0, options.maxLength));
_length=options.maxLength;
}
var _left = $thiz.position().left;
var _top = $thiz.position().top;
var _width = $thiz.width();
var _height = $thiz.height();
$show.text(_length + '/' + options.maxLength);
$show.css({
'left' : _left+ _width - 40,
'top' : _top + _height - 8
});
});
this.keydown(function(event){
if(event.keyCode==8||event.keyCode==46
||event.keyCode==37||event.keyCode==39
||event.keyCode==38||event.keyCode==40
||event.keyCode==35||event.keyCode==36){
return true;
}
if($(this).val().length>= options.maxLength){
var selection=$(this).getSelection();
if(selection.selectionEnd>selection.selectionStart){
return true;
}else{
return false;
}
}else{
return true;
}
});
this.focus(function(){
$show.fadeIn('slow');
});
this.blur(function(){
$show.fadeOut('slow');
});
};
})(jQuery);
用例:
$("#test").inputlimiter({maxLength:10});
效果: