`
suxing
  • 浏览: 202709 次
  • 性别: Icon_minigender_1
  • 来自: 遵义
社区版块
存档分类
最新评论

文本框字数提示jquery插件

阅读更多

写了一个在文本框右上角显示已输入字数的插件,我写的第二个jquery插件,总算是有点实用价值。

/**
*WordCount 1.0
*Author: Xing Su
*E-mail: suxing.sir@gmail.com
**/
(function($) {
   $.fn.WordCount = function(options) {
      var opts = $.extend({}, $.fn.WordCount.defaults, options);
	  var temp=$('#'+opts.ID);
	  var getlen=function($this){
	     return $this.val().length;
	  }
	  var showlen=function($this,obj){
		  obj.text(getlen($this)+'/'+opts.MaxWord);
		  var color;
		  if(getlen($this)>opts.MaxWord){
		     color=opts.Color2;
	          }else{
		     color=opts.Color;
		  }
		  obj.css('color',color);
	  }
	  if(temp.length==0){
	     temp=$('<div id="'+opts.ID+'"></div>');
		 temp.css({position:'absolute',display:'none'});
		 temp.css({width:opts.Width,height:opts.Height,color:opts.Color,'text-align':opts.textAlign});
		 $(document.body).append(temp);
	  }
	  return this.each(function(){
	     $(this).focus(function(){
	  	    var left=Math.floor($(this).outerWidth()+$(this).offset().left-opts.Width+opts.offsetLeft);
    		var top=Math.floor($(this).offset().top-opts.Height+opts.offsetTop);
            temp.css({top:top,left:left}).text(getlen($(this))+'/'+opts.MaxWord).fadeIn('fast');
		 });
		 
		 $(this).blur(function(){
		    temp.fadeOut('fast');
		 });
		 
		 $(this).keyup(function(){
		    showlen($(this),temp);
		 });
		 
		 $(this).keydown(function(){
		    showlen($(this),temp);						  
		 });		 
	  });
   }

   $.fn.WordCount.defaults = {
      Width:70,
	  Height:15,
	  MaxWord:1024,
	  ID:'wordcount',
	  Color:'#FFFFFF',
	  Color2:'#FF0000',
	  offsetTop:0,
	  offsetLeft:0,
	  textAlign:'right'
   }

})(jQuery);

 使用也简单:

$('textarea').WordCount();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics