[TimLinux] JavaScript table的td内容超过宽度缩为三个点

1. 思路

  • CSS控制td内容自动缩为三个点
  • JS控制鼠标悬浮显示td全部内容

2. 实现

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Table/td自动隐藏内容</title>
    <link rel="stylesheet" href="my.css" />
</head>
<body>
    <table id="idMyTable">
    <tr>
        <td>这是一个正常显示的内容</td>
        <td>这是一个自动隐藏超长文本内容的内容,剩下的内容将根据款冬自动隐藏,功能能够正常执行。</td>
    </tr>
    </table>
    <script type="application/javascript" src="my.js"></script>
</body>
</html>

CSS代码:

table {
    width: 400px;
    border-collapse: collapse; /* 为表格设置合并边框模型 */
    table-layout: fixed; /* 设置表格布局算法,只有设置这个值后面的td属性才有效 */
}

td {
    border: 1px solid blue;
    word-break: keep-all; /*在恰当的断字点进行换行 */
    white-space: nowrap; /* 规定段落中的文本不进行换行 */
    overflow: hidden; /* 当内容溢出元素框时发生的事情 */
    text-overflow: ellipsis; /* 当文本溢出包含元素时发生的事情, ellipsis含义为省略号 */
}

JS代码:

window.onload = function () {
    var allTds = document.getElementsByTagName('td');
    for (var i = 0; i < allTds.length; i++) {
        var td = allTds[i];
        td.onmouseover = function (ev) {
            if (this.clientWidth < this.scrollWidth) {
                this.setAttribute('title', this.textContent);
            }
        };
        td.onmouseleave = function (ev) {
            this.removeAttribute('title');
        };
    }
};

3. 效果

 

posted @ 2018-08-25 09:18  TimLinux  阅读(227)  评论(0编辑  收藏  举报