需求:表单填写信息过长,提交按钮在顶部需要一直在可视区,公司信息也固定显示在底部不被遮盖,于是要求只要中间内容部分,填写信息滚动条滚动内容
实现效果:
组件:
<template>
<div class="scrollbar-container">
<el-scrollbar class="scroll" id="scrollContent" :style="{ height: height ,width:width}">
<slot></slot>
</el-scrollbar>
</div>
</template>
<script>
import { calculateHeight } from "@/utils/calcHeight";
export default {
props: {
//要减去高度的div的class el-scrollbar下面的div
cutClassNames:{
type:Array,
default:()=>[]
}
},
components: {},
data() {
return {
height: "100%",
width:"100%",
};
},
created() {},
mounted() {
window.addEventListener("resize", this.handleResize);
},
beforeDestroy(){
window.removeEventListener("resize",this.handleResize);
},
watch: {
cutClassNames: {
handler(val) {
this.handleResize();
},
immediate:true
},
},
methods: {
handleResize(){
this.$nextTick(()=>{
this.height=calculateHeight(this.cutClassNames,50)+"px";
})
},
},
};
</script>
<style lang="scss" scoped>
</style>
计算滚动区域高度:calcHeight.js
export const caculateOtherHeight=function(cutClassNames=[]) {
let total = 0;
if( cutClassNames&& cutClassNames.length>0){
cutClassNames.forEach((className) => {
const h =document.getElementsByClassName(className)[0].offsetHeight || 0;
total = total + h;
});
}
return total;
}
//计算减后的实际高度
export const calculateHeight=function(cutClassNames=[],cutHeight=0) {
let otherHeight=caculateOtherHeight(cutClassNames);
const windowHeight = window.innerHeight; // 窗口高度
const top = document.getElementById("scrollContent").getBoundingClientRect().top;//滚动区域到顶部距离
const pageContent = document.getElementById("pageContent");
let bottomPx = window.getComputedStyle(pageContent).paddingBottom||0;
let bottomPxM=window.getComputedStyle(pageContent).marginBottom||0;
const bottom = Number(bottomPx.replace("px", "") || 0);
const bottomM=Number(bottomPxM.replace("px", "") || 0);
const total = top + bottom+bottomM + otherHeight;
const height = windowHeight - total-cutHeight;
return height;
}
export const handleWindowOnresize=function(){
window.onresize = () => {
return (() => {
calculateHeight();
})();
};
}
注:主内容区域加id="pageContent" 参考 基于ElementUI的el-table滚动条处理_Holly31的博客-CSDN博客
页面使用:
<blScrollContent >
<el-form>
滚动内容
</el-form>
</blScrollContent>
全局样式修改滚动条样式:
不写这个,横向滚动条显示会有问题
.el-scrollbar__wrap{
overflow-x: auto;
padding-bottom: 20px;
height: calc(100% + 20px);
}