html:
<div class="ellipsis">
夜空中最亮的星/请指引我走出去/夜空中最亮的星 是否知道/那曾与我同心的身影 如今在哪里/夜空中最亮的星 是否在意/
</div>
js:
$(document).ready(function(){ //限制字符个数 $(".ellipsis").each(function(){ var maxwidth=39; if($(this).text().length>maxwidth){ $(this).text($(this).text().substring(0,maxwidth)); $(this).html($(this).html()+'…'); alert(); } }); });
另一种:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>输入字符限制</title> <script type="text/javascript" src="js/jquery-1.11.0.js"></script> <style> .tucao_dl { width: 518px; overflow: hidden; } .tucao_dl dt { clear: both; margin-top: 5px; } .tucao_dl dt textarea { background: none; border: none; border: 1px solid #ddd; width: 510px; height: 135px; line-height: 24px; padding-top: 3px; font-size: 14px; color: #999; font-family: '微软雅黑'; resize: none; } .tucao_dl dt i { color: #ff6600; } .tucao_dl dd { float: left; color: #999; font-family: '微软雅黑'; font-size: 14px; } .tucao_dl dd i { color: #ff6600; } .focusing{background-color: rgba(22,219,10,0.5);} </style> </head> <body> <dl class="tucao_dl" > <dt> <textarea id="OtherText" title="http://www.cnblogs.com/Han39/。" class="feedbackT" onkeyup="maxlength(this)" onfocus="editAdvice()"></textarea> </dt> <dd>您还可以输入<i>200</i>字</dd> </dl> </body> <script> $(document).ready(function(){ $('#OtherText').each(function(){ $(this).val($(this).attr('title')); }).focus(function(){ if(this.value == $(this).attr('title')){ $(this).val('').addClass('focusing'); }; }).blur(function(){ if(this.value == ''){ $(this).val($(this).attr('title')).removeClass('focusing'); }; }); }); function maxlength(obj){; var num = $(obj).val().length; if(200-num>=0){ $('.tucao_dl dd').find('i').text(200-num); } obj.value = obj.value.slice(0, 200); } function editAdvice(){ var advice=removeAllSpace($("#OtherText").val()); var title=removeAllSpace($("#OtherText").attr("title")); if(advice==null ||advice.length<=0 || advice ==title){ $("#OtherText").text(""); } } </script> </html>