项目经历——截取超出长度的字符串,鼠标移动到上面显示全部内容

来源:互联网 发布:同床异梦的人工智能 编辑:程序博客网 时间:2024/06/03 17:48

  项目进行的越来越有感觉了^_~ ,当然其中遇到的问题也不少。今天在调试前台的时候,出现了一个不算问题的小问题,在这里分享一下。

问题背景:

  我们页面布局的时候,因为用div+table这种布局格式,所以对于table中的单元格内容的长度有一定限制,如果长度过长,就会影响整个table的布局,进而波及整个页面的布局效果。这样就要求我们对table单元格中的内容进行截取,并且当鼠标移动到上面的时候显示出来隐藏的内容。


相关代码:


  字符串截取:

        ///   <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))                //   throw   new   NullReferenceException( "原字符串不能为空 ");                 return oldStr + endWith;            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>(超链接)标签的title属性,当鼠标移动到上面,会自动显示<a>标签中title属性绑定的数据

<td class="auto-style4"><a href="#"target="_blank" title="<%#Eval("CompanyStyle") %>"> <%# StringTruncat( Eval("CompanyName").ToString(), 4 , "...") %></a></td>        


在项目中的实例源码:

<%--绑定最新注册的公司--%><marquee onmouseover="this.stop()" onmouseout="this.start()" scrollamount="1" vspace="5" scrolldelay="60" direction="up" behavior="scroll" width="95%" height="120"><asp:Repeater ID="GetCompanyInfo" runat="server"><HeaderTemplate>                   <table id="GetCompanyInfo" cellspacing="12"   ></HeaderTemplate><ItemTemplate>     <tbody>         <tr>                                                                  <td class="auto-style4"><a href="#"target="_blank" title="<%#Eval("CompanyStyle") %>"> <%# StringTruncat( Eval("CompanyName").ToString(), 4 , "...") %></a></td>            <td><%# ((DataRowView )Container.DataItem)["CompanySpokenMan"] %></td>            <td><%# ((DataRowView )Container.DataItem)["CompanyAddress"] %></td>          </tr>     </tbody></ItemTemplate><FooterTemplate>      </table></FooterTemplate>    </asp:Repeater></marquee>

效果图



  

  实际上,在牛腩老师的视频中,也曾讲过这个问题,但当时只是简单的实现,并没有想到以后会用到。所以没怎么留意,现在这也算重新学习一下,也应了师哥的那句话:学习是一个反复的过程。另一方面,这个看似简单的小功能,在网站文本编辑显示中可以发挥出更出色的用户体验,也算是全心全意为上帝服务吧~~~