现在的位置: 首页 > 综合 > 正文

字符串过长,截取的几种方法。

2012年01月07日 ⁄ 综合 ⁄ 共 2333字 ⁄ 字号 评论关闭

1.通过css进行截取。不过要区分ie,ff等浏览器。   

<style type="text/css">
        .ds
        {
            max-width: 95px; /*层的宽度。*/
        }
        .as
        {
            display: block; /*定义为块级*/
            width: 90px; /*要显示文字的宽度*/
            float: left; /*左对齐*/
            overflow: hidden; /*超出的部分隐藏起来。*/
            white-space: nowrap; /**/
            padding-right: 10px; /*文字距离右侧7像素。*/
            text-overflow: ellipsis; /* 支持 IE 不显示的地方用省略号...代替*/
            -o-text-overflow: ellipsis; /* 支持 Opera  不显示的地方用省略号...代替*/
        }
        .ds:after
        {
            content: "...";
        }
        /* 支持 Firefox */</style>

2.通过自定义方法截取

 public static string[] Intercept(string input, int p)
        {
            String[] Strinput 
=new String[2];
            Encoding encode 
= Encoding.GetEncoding("gb2312");
            input 
= input ?? String.Empty;
            
byte[] byteArr = encode.GetBytes(input);
            
if (byteArr.Length <= p)
            {
                Strinput[
0= input;
                Strinput[
1= "";
                
return Strinput;
            }

            int m = 0, n = 0;
            
foreach (byte b in byteArr)
            {
                
if (n >= p) break;
                
if (b > 127) m++//重要一步:对前p个字节中的值大于127的字符进行统计
                n++;
            }
            
if (m % 2 != 0) n = p + 1//如果非偶:则说明末尾为双字节字符,截取位数加1
            Strinput[0]= encode.GetString(byteArr, 0, n);
            Strinput[
1= encode.GetString(byteArr, n, byteArr.Length - n);
            
return Strinput;
        }

3.通过js截取。

 

  <script type="text/javascript">

        $(function () { myfunction(); })

        function myfunction() {

            var jj = document.getElementById("jj").innerText;

            if (jj.length>100) {
                document.getElementById(
"jj").innerHTML = jj.substring(099+ "<span id='span1'><a href='#' onclick='display(0)'>...展开</a></span><span id='span2' style='display:none;'>" + jj.substring(99, jj.length) + "<a  onclick='display(1)' href='#'> 收起 </a></span>"
            }
        }

        function display(id) {
            
if (id == 0) {
                document.getElementById(
"span1").style.display = "none";
                document.getElementById(
"span2").style.display = "";
            } 
else {
                document.getElementById(
"span1").style.display = "";
                document.getElementById(
"span2").style.display = "none";
            }
        }

    </script>

 

抱歉!评论已关闭.