vue中獲取滾動table的可視頁面寬度,調整表頭與列對齊(每列寬度不都相同)


mounted() {
     // 在mounted中監聽表格scroll事件
this.$refs.scrollTable.addEventListener( 'scroll',(event) => { this.adjustTable(event); }); }, ......
// target中的屬性很多,可以通過控制台查看—-clientWidth可以獲取除滾動條外的可視區域寬度
adjustTable(event) {
            this.clientWidth = event.target.clientWidth;
        },
                

獲取clientWidth,可以調整表頭與列對齊(最后一列的寬度不設置)

<table class="cl-body-table" cellpadding="0" cellspacing="0">
        <thead  :style="{'width':clientWidth+'px'}">
            <th  style="width:8%"></th>
            <th class="cl-thead-th"></th>
        </thead>
        <tbody></tbody>
</table>

.......
// 表格滾動
  table tbody {
    display: block;
    height: 495px;
    overflow-y: auto;
    overflow-x: hidden;
  }
// 表頭固定
  table thead,
  tbody tr {
    display: table;
    table-layout: fixed; /* 使用表格固定算法 必須配合上面一起使用 */
    width: 100%;
  }
//列寬度
.cl-thead-th {
        &.is-not-last {
            width:13.142857143%  // 最后一列不設寬度,才能表頭與列對齊
        }
    }

網上最簡單的表頭與列對齊,由於我第一列的寬度與其他列寬度不同,導致始終不能對齊。因此我采用以下方法無效

// 表格滾動
table tbody {
    display: block;
    height: 495px;            
    overflow-y: auto;
    overflow-x: hidden;
}
// 表頭固定
table thead,
tbody tr { 
    display: table;
    table-layout: fixed; /* 使用表格固定算法 必須配合上面一起使用 */
    width: 100%;
}
// 調整表頭與列對齊
table thead {
    width:calc(100%-2em)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM