• C#截取指定长度字符超出部分以"..."代替,用于处理过长的标题


    在做网站的时候经常遇到需要显示的东西太长,此时我们通常会将它们按一定的长度截取,然后在其后面加上省略号。当鼠标移到上面时,就会显示出完整的内容。就像下面这样:





    要实现此效果,需要用到下面这个截取字符串的函数。相信不用我废话,大家一看注释就能明白是如何实现的。、

            ///   <summary> 
            ///   将指定字符串按指定长度进行截取并加上指定的后缀
            ///   </summary> 
            ///   <param   name= "oldStr "> 需要截断的字符串 </param> 
            ///   <param   name= "maxLength "> 字符串的最大长度 </param> 
            ///   <param   name= "endWith "> 超过长度的后缀 </param> 
            ///   <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns> 
            public static string StringTruncat(string oldStr, int maxLength, string endWith)
            {
                //判断原字符串是否为空
                if (string.IsNullOrEmpty(oldStr))
                    return oldStr + endWith;
    
    
                //返回字符串的长度必须大于1
                if (maxLength < 1)
                    throw new Exception("返回的字符串长度必须大于[0] ");
    
    
                //判断原字符串是否大于最大长度
                if (oldStr.Length > maxLength)
                {
                    //截取原字符串
                    string strTmp = oldStr.Substring(0, maxLength);
    
    
                    //判断后缀是否为空
                    if (string.IsNullOrEmpty(endWith))
                        return strTmp;
                    else
                        return strTmp + endWith;
                }
                return oldStr;
            } 

      



    光有这个函数还不够,需要在页面的代码设计中加入一段HTML代码,用来调用此函数,并实现在鼠标指向它是显示其完整内容。

    <a href="http://www.cnbeta.com/articles/201461.htm"  title='MSDN和TechNet订阅者明天可下载Windows8最终版'><%#StringTruncat("MSDN和TechNet订阅者明天可下载Windows8最终版", 18, "...")%> </a>

      


    简单的几行代码,实现了一个贴心的小功能,让用户在浏览你的网站时,感觉很舒服,这就是作为程序员最大的幸福!时刻谨记:全心全意为用户着想!

  • 相关阅读:
    CS224n, lec 10, NMT & Seq2Seq Attn
    CS231n笔记 Lecture 11, Detection and Segmentation
    CS231n笔记 Lecture 10, Recurrent Neural Networks
    CS231n笔记 Lecture 9, CNN Architectures
    CS231n笔记 Lecture 8, Deep Learning Software
    CS231n笔记 Lecture 7, Training Neural Networks, Part 2
    pytorch坑点排雷
    Sorry, Ubuntu 17.10 has experienced an internal error
    VSCode配置python插件
    tmux配置与使用
  • 原文地址:https://www.cnblogs.com/liushuijinger/p/2638929.html
Copyright © 2020-2023  润新知