需求:el-table列过长,想通过关键字匹配出表头,直接在可视窗口内
代码:
//通过关键字匹配出具体的表头所在的th
findHeaderCellByText(text) {
// 查找表格DOM元素
const table = this.$在这里插入代码片refs.myTable.$el;
if (!table) return null;
// 查找表头行(通常是第一个thead中的tr)
const thead = table.querySelector("thead");
if (!thead) return null;
// 查找表头单元格
const headerCells = thead.querySelectorAll("th");
for (let i = 0; i < headerCells.length; i++) {
const cellText = headerCells[i].innerText.trim(); // 获取单元格文本并去除空格
if (cellText.includes(text)) {
return headerCells[i]; // 返回匹配的单元格DOM元素
}
}
return null; // 如果没有找到,返回null
},
//通过点击按钮来出发匹配操作
handlePositionKeyWord() {
//在data中定义了positionKeyWord,是需要匹配的关键字
const headerCell = this.findHeaderCellByText(this.positionKeyWord);
if (headerCell) {
//先让滚动条到初始位置,这样才能获取到匹配出来的表头距离可是窗口的距离
this.setTableScrollLeft(0);
setTimeout(() => {
//获取到表头距离可是窗口的距离
const rect = headerCell.getBoundingClientRect();
const leftDistanceToScreen = rect.left + window.pageXOffset;
//调用滚动条的位置
this.setTableScrollLeft(leftDistanceToScreen);
}, 100);
}
},
//横向移动的方法
setTableScrollLeft(scrollLeftPosition) {
const tableBodyWrapper = this.$refs.myTable.$el.querySelector(
".el-table__body-wrapper"
);
if (tableBodyWrapper) {
// 设置滚动位置
tableBodyWrapper.scrollLeft = scrollLeftPosition;
}
},