function GetLength(str) { ///获得字符串实际长度,中文2,英文1 ///要获得长度的字符串 var realLength = 0, len = str.length, charCode = -1; for (var i = 0; i < len; i++) { charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) realLength += 1; else realLength += 2; } return realLength; }; jQuery.fn.CRselectBox = jQuery.fn.sBox = function(options){ options = $.extend({ animated : false },options); var _self = this; /*构建结构*/ var _parent = _self.parent(); var wrapHtml = '
'; var $wrapHtml = $(wrapHtml).appendTo(_parent); var selectedOptionValue = _self.find("option:selected").attr("value"); var selectedOptionTxt = _self.find("option:selected").text(); var name = _self.attr("name"); var id = _self.attr("id"); var inputHtml = ''; $(inputHtml).appendTo($wrapHtml); var inputTxtHtml = ''; $(inputTxtHtml).appendTo($wrapHtml); var aHtml = ''+selectedOptionTxt+''; $(aHtml).appendTo($wrapHtml); var ulHtml = ''; var $ulHtml = $(ulHtml).appendTo($wrapHtml); var liHtml = ""; _self.find("option").each(function(){ if($(this).attr("selected")){ liHtml += '
  • '+$(this).text()+'
  • '; }else{ liHtml += '
  • '+$(this).text()+'
  • '; } }); $(liHtml).appendTo($ulHtml); /*添加效果*/ $( $wrapHtml, _parent).hover(function(){ $(this).addClass("CRselectBoxHover"); },function(){ $(this).removeClass("CRselectBoxHover"); }); $(".CRselectValue",$wrapHtml).click(function(){ $(this).blur(); if( $(".CRselectBoxOptions",$wrapHtml).is(":hidden") ){ if(options.animated){ $(".CRselectBoxOptions").slideUp("fast"); $(".CRselectBoxOptions",$wrapHtml).slideDown("fast"); }else{ $(".CRselectBoxOptions").hide(); $(".CRselectBoxOptions",$wrapHtml).show(); } } return false; }); $(".CRselectBoxItem a",$wrapHtml).click(function(){ $(this).blur(); var value = $(this).attr("rel"); var txt = $(this).text(); $("#"+id).val(value); $("#"+id+"_CRtext").val(txt); var txtValue=$("#"+id+"_CRtext").val(); if(GetLength(txtValue)>20){ $(".CRselectBox").css("background","none") }else{ $(".CRselectBox").css("background","#FFFFFF url(/pic/select_box_off.gif) no-repeat right center") }; $(".CRselectValue",$wrapHtml).text(txt); $(".CRselectBoxItem a",$wrapHtml).removeClass("selected"); $(this).addClass("selected"); if(options.animated){ $(".CRselectBoxOptions",$wrapHtml).slideUp("fast"); }else{ $(".CRselectBoxOptions",$wrapHtml).hide(); } return false; }); $(document).click(function(event){ if( $(event.target).attr("class") != "CRselectBox" ){ if(options.animated){ $(".CRselectBoxOptions",$wrapHtml).slideUp("fast"); }else{ $(".CRselectBoxOptions",$wrapHtml).hide(); } } }); _self.remove(); return _self; }