以下記錄是個人開發(fā)過程中遇到的問題:
效果.gif
當(dāng)列表內(nèi)容部分可見時,保持橫向滾動條在下方。
實(shí)現(xiàn)
原理
1.這里涉及到兩個Dom
元素蚪腐,類名分別為 el-table__body-wrapper
二汛、el-table__body
通過觀察發(fā)現(xiàn)橫向滾動條在于el-table__body-wrapper
上,el-table__body
則是實(shí)際的列表內(nèi)容婆硬,當(dāng)el-table__body
寬度超出el-table__body-wrapper
時就會出現(xiàn)橫向滾動條。
2.因此只需要動態(tài)的修改el-table__body-wrapper
的height
即可實(shí)現(xiàn)想要的效果歉井。
3.在頁面發(fā)生滾動柿祈、頁面大小改變以及數(shù)據(jù)源更新的時候?qū)?code>el-table__body-wrapper的height
進(jìn)行調(diào)整。
代碼
這里是通過mixin方式的實(shí)現(xiàn)哩至。
let el;
let tableBodyWrapDom = document.getElementsByClassName('.el-table__body-wrapper');
let tableBodyDom = document.getElementsByClassName('.el-table__body')
function handle() {
if (!el) return;
// top為dom上側(cè)距離可視窗口頂部的值
const { top:tableBodyDomTop } = tableBodyWrapDom.getBoundingClientRect();
if (tableBodyDomTop > window.innerHeight || tableBodyWrapDom.classList.contains('is-scrolling-none')) {
// 此時列表在可視窗口的下側(cè)不可見區(qū)域躏嚎,因此不做任何修改
tableBodyWrapDom.style.height = 'unset'
tableBodyWrapDom.style.marginBottom = 'unset';
} else {
// 窗口高度 - 列表距頂部值 且 不超過自身實(shí)際值
let wrapHeight = Math.min(window.innerHeight - tableBodyDomTop, tableBodyDom.offsetHeight);
tableBodyWrapDom.style.height = wrapHeight + 'px';
// 需要用marginBottom填充,以保持列表原有高度菩貌,避免頁面的縱向滾動條變化導(dǎo)致頁面滾動的不流暢
// 可以通過注釋這一行代碼觀察其效果差異
tableBodyWrapDom.style.marginBottom = (tableBodyDom.offsetHeight - wrapHeight) + 'px';
// console.log(tableBodyWrapDom.style.marginBottom,'marginBottom')
}
}
export default {
mounted() {
el = this.$el; // 當(dāng)前組件的Dom對象卢佣,避免操作到本組件之外的Dom
tableBodyWrapDom = el.querySelector('.el-table__body-wrapper');
tableBodyDom = el.querySelector('.el-table__body');
// 監(jiān)聽事件
window.addEventListener('scroll', handle,true);
window.addEventListener('resize', handle,true);
},
destroyed() {
// 在組件銷毀時取消監(jiān)聽
window.removeEventListener('scroll', handle,true);
window.removeEventListener('resize', handle,true);
},
watch: {
list() {
// 當(dāng)列表數(shù)據(jù)源發(fā)生變化時,再次觸發(fā)
this.$nextTick( handle);
}
}
}
watch中監(jiān)聽的list:在引用混合的組件中
<el-table
ref="brandTable"
:data="list" <----
style="width: 100%"
@selection-change="handleSelectionChange"
v-loading="listLoading"
border
>
....
</el-table>