调整浏览器大小时文本上的CSS省略号

CSS ellipsis on text when resizing browser

本文关键字:CSS 省略号 文本 浏览器 小时 调整      更新时间:2024-05-06

我有一个宽度设置为100%的<table><td>中有一个div,它包含一个文本字符串,如果文本宽度溢出,我想添加一个省略号。

在javascript中,我将<div>的宽度设置为<td>的宽度,这在加载(或刷新)时运行良好,但我无法使其运行onresize

(不用担心我在这里实际在做什么。这是我为了这个问题简化的一个更大表格的一部分。)

有人能建议我如何将文本省略号为onresize吗?

function doThis() {
    $('.divClass').css('width', $(".tdClass").css('width'));
}
.divClass {
    width:0px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="doThis()" onresize="doThis()">
<table style="width:100%">
    <tr>
        <td class="tdClass">
            <div class="divClass">
                the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog 
            </div>
        </td>
    </tr>
</table>
</body>

如果不处理主体属性,请尝试将调整大小与浏览器窗口绑定

$(window).resize(function(){
   doThis()
});

我想这只能用css完成。你能试试这个代码吗

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<style>
   /* Added new style property */
table,tr,td,tbody{
    width:100%;
    display:inline-block;
}
td{
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
}
  /* New style property end her */
</style>
</head>
<body>  <!-- //removed onload & onresize -->
<table>
    <tr>
        <td>  <!-- // removed the div -->
             the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog 
        </td>
    </tr>
</table>
</body>
</html>

div是块元素,所以如果你不给任何宽度,它会自动取td的宽度。这意味着不需要脚本。

尝试使用display:block属性使表响应,以便div在调整大小时可以从td元素获得适当的宽度。

table, thead, tbody, th, td, tr {
    display: block;
    height: auto;
}