在 ASP.NET GridView 上,我有一个从数据库打印字符串的字段。此数据的范围可以是 10 到 100 个字符。当它比正常情况长时,字段会对数据进行自动换行,使该行比其他行占用更多的垂直空间。我想截断任何不适合该行的数据,然后在其旁边有一个“...”以指示还有更多数据。我不需要让它们调整大小,我只是不想要任何不同高度的行。我希望这可以在客户端动态完成,以达到搜索引擎优化的目的。

请参阅 ActiveWIdgets 网格在这里, ,然后调整公司名称的大小,使其不适合。您会注意到它没有包装内容,但它恰恰做了我想做的事情。

如何将此技术应用于 ASP.NET GridView?我假设涉及一些Javascript。如果这是真的,我更愿意 不是 使用像 jQuery 这样的库(不要问为什么——我不允许在这个项目中使用外部依赖项)。

有帮助吗?

解决方案

目录

  1. 问题说明
  2. 一种解决方案的图示

问题说明
将以下 HTML 复制到您的浏览器(至少是 Firefox 和 Internet Explorer 7,但您也应该尝试 Opera):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        div, td
        {
            width: 100px;
            border: solid 1px black;
            white-space: nowrap;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <div>
        content content content content content content
    </div>
    <table cellpadding="0" cellspacing="0">
        <tbody>
            <tr>
                <td>
                    content content content content content content
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

请注意, td 元素不会隐藏溢出的内容。只有 div 元素现在如何执行此操作。互联网浏览器的 td 元素甚至不知道如何停止换行内容。

严格来说,根据 标准, , 这 td 元素不支持 white-space 规则。这 divth 元素可以。

一种解决方案的图示
这是 问题的解决方案(在 Opera、Firefox 和 Internet Explorer 7 中测试):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        td
        {
            border: solid 1px black;
        }
        div
        {
            width: 100px;
            white-space: nowrap;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <table cellpadding="0" cellspacing="0">
        <tbody>
            <tr>
                <td>
                    <div>
                        content content content content content content
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

其他提示

如果您知道您的用户正在使用 Internet Explorer,则可以使用以下仅限 IE 的 CSS:

td.nooverflow
{
  text-overflow:ellipsis;
}

然后将要固定宽度的列的 ItemStyle 设置为 <ItemStyle CssClass='nooverfolow'/> (您需要使用 CSS 才能使其适合您的应用程序)

不幸的是,由于这仅适用于 IE,因此对于其他浏览器,可以使用一些 hack 来模拟相同的事情:

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top