ElementUi中select框在页面滚动时el-option超出元素区域的问题解决
作者:sᴜᴘᴇʀ菜酱
前几天在开发一个需求时,无意发现了select超出区域el-option会浮出来问题,我整个人都不淡定了😱,想着正常人应该都不会像我这样反人类操作吧😅... 但是秉着对技术的执着,有问题咱就迎难而上,啥大风大浪没见过的....

既然已经发现问题,我就开始琢磨为什么会产生这个问题🤔 头脑风暴中,经过思考有了下面的见解...
1.select 默认是插入到body元素的,因为他层级很高,所以滚动时el-option 会浮出来

2.那是不是把popper-append-to-body 改为false 就可以了呢?答案是不行,因为会被外面父盒子的overflow: hidden隐藏掉。

🤔思考片刻后,我尝试了两种方式去解决这种问题^ _ ^
第一种方法
1.select添加 popper-append-to-body 为false
// 添加 popper-append-to-body 为false
<el-select v-model="row.attribute_id"
:popper-append-to-body="false"
@change="handleDiscountAttribute(row)">
<el-option v-for="(attr,aIdx) in row.attributeOption"
:key="aIdx"
:label="attr.attribute_name"
:value="attr.id" />
</el-select>2.修改element table的底层样式
/deep/.table-wrapper {
border: 1px solid #e9ecf0;
border-bottom: 0;
// 修改element的底层样式
.cell {
overflow: visible;
}
.el-table__body-wrapper {
overflow: overlay;
}
}【效果展示】
虽然超出区域没有浮出来,但是仔细会发现,el-option有时候会从底部先出往上展开,而且展开的数据如果太多需要滚动才能选择,总的来说体验感不太好。

第二种方法 ,监听滚动的时候,收起el-option,这也是我比较推荐的方法。
1.进入页面时获取表格实例,监听滚动事件
let operableTree = null;
// 获取表格的dom, 监听滚动事件
let box = document.querySelector('.table-wrapper .el-table__body-wrapper');
box.addEventListener(
'scroll', () => {
clearTimeout(operableTree);
// 滚动时调用select 失焦的方法 为了避免一直监听,可以判断是否有点击选择器
this.selectIndex !== -1 && (operableTree = setTimeout(() => {
this.$refs[`treeSelect-${this.selectIndex}`].blur();
this.selectIndex = 1;
}, 100));
},
false
);
}, 500);
2.给select添加ref标识,添加聚焦方法handleFocus,获取点击的是哪个选择框,表格滚动时 只需要对这个选择框进行失焦操作。this.$refs[`treeSelect-${this.selectIndex}`].blur();
<el-table :data="tableData"
max-height="550"
class="table-wrapper">
<el-table-column label="商品属性"
width="250">
<template v-slot="{row, $index}">
<!-- select 增加ref -->
<el-select :ref="`treeSelect-${$index}`"
v-model="row.attribute_id"
@focus="handleFocus(row, $index)"
@change="handleDiscountAttribute(row)">
<el-option v-for="(attr,aIdx) in row.attributeOption"
:key="aIdx"
:label="attr.attribute_name"
:value="attr.id" />
</el-select>
</template>
</el-table-column>
</el-table>
data() {
return {
tabeleData: [], // 表格数据
selectIndex: -1, // 点击的select的位置
};
},
methods: {
handleFocus(e, index) {
this.selectIndex = index;
},
}【效果展示】

到此这篇关于ElementUi中select框在页面滚动时el-option超出元素区域的问题解决的文章就介绍到这了,更多相关Element el-option超出元素内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
