zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JQuery控制内容长度超出规定长度显示省略号

jQuery控制 显示 内容 长度 超出 规定 省略号
2023-06-13 09:15:27 时间
长度超出规定长度,显示省略号

设置class为displayPart,

设置自定义属,displayLength可显示长度(不包含...),双字节字符,长度*2,
复制代码代码如下:

<scripttype="text/javascript">
$.fn.extend({
displayPart:function(){
vardisplayLength=100;
displayLength=this.attr("displayLength")||displayLength;
vartext=this.text();
if(!text)return"";

varresult="";
varcount=0;
for(vari=0;i<displayLength;i++){
var_char=text.charAt(i);
if(count>=displayLength)break;
if(/[^x00-xff]/.test(_char))count++;//双字节字符,//[u4e00-u9fa5]中文

result+=_char;
count++;
}
if(result.length<text.length){
result+="...";
}
this.text(result);
}
});

$(function(){
$(".displayPart").displayPart();
});

</script>

复制代码代码如下:

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>NewDocument</title>
<metaname="Generator"content="EditPlus">
<metaname="Author"content="">
<metaname="Keywords"content="">
<metaname="Description"content="">
<scripttype="text/javascript"src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>

<body>
<h2>helloworld</h2>

<divstyle="width:500px;">
helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld!!!
</div>
<hr>
<h2>hello</h2>
<divclass="displayPart"displayLength="40">helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworldhelloworld
</div>
</body>
</html>