<div class="coupon-exchange clearfix"> <div class="code-input"> <input type="text" placeholder="请输入兑换码" class="input" id="couponExchangeInput"/> <i class="icon-clear" id="couponExchangeClear"></i> </div> <div class="btn-exchange" id="couponExchangeBtn">兑换</div> </div>
function couponExchange() { //中文输入,输入完成后才触发事件 var flag = true; $('#couponExchangeInput').on('compositionstart',function(){ flag = false; }); $('#couponExchangeInput').on('compositionend',function(){ flag = true; }); $('#couponExchangeInput').on('input', function(){ var _this = this; setTimeout(function(){ if(flag){ var _val = $(_this).val(); $('#couponExchangeBtn').addClass('active'); $('#couponExchangeClear').css('display', 'block'); if(_val == ''){ $('#couponExchangeBtn').removeClass('active'); $('#couponExchangeClear').hide(); } if(strlen(_val) > 100){ var _cutVal = cut_str(_val, 50); $(_this).val(_cutVal); } } },0); }); $('#couponExchangeClear').click(function(){ $('#couponExchangeBtn').removeClass('active'); $('#couponExchangeClear').hide(); $('#couponExchangeInput').val('').focus(); }); $('#couponExchangeInput').blur(function(){ var _val = $(this).val(); if(strlen(_val) > 100){ var _cutVal = cut_str(_val, 50); $(this).val(_cutVal); } }); $('#couponExchangeBtn').click(function(){ if($(this).hasClass('active')){ console.log(1); } }); } //获取字符串的长度,一个中文占位两个字符长度 function strlen(str) { var len = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) { len++; } else { len += 2; } } return len; } //截取字符串的长度,一个中文占位两个字符长度 function cut_str(str, len){ var char_length = 0; for (var i = 0; i < str.length; i++){ var son_str = str.charAt(i); encodeURI(son_str).length > 2 ? char_length += 1 : char_length += 0.5; if (char_length >= len){ var sub_len = char_length == len ? i+1 : i; return str.substr(0, sub_len); break; } } }