背景:
1、需求在希望文件夹列表过长时右下角展示一键置顶功能
2、使用element-ui组件库,backtop组件
3、页面结构:
<template>
<div class="box">
<div class="list"></div>
<ceshi target=".box" :right="0">
我是一键指定按钮
</ceshi>
</div>
</template>
<script>
import ceshi from "./ceshi.vue";
export default {
name: "home_11",
components: {
ceshi
},
data() {
return {
}
},
};
</script>
<style>
.box {
width: 1000px;
height: 1000px;
border: 1px solid red;
background: red;
position: relative;
overflow: auto;
margin: 0 auto;
}
.list {
width: 100%;
height: 2000px;
position: relative;
background: green;
}
</style>
4、页面效果
解释
1、你会发现右侧一键置顶按钮他会随着滚动条滚动而改变位置,是因为定位父元素这是了overflow:auto。原理不太清楚为何导致,但是问题现象如此,
2、有人可能会发现,我用的组件不是固定定位展示在视口的右下角,是因为组件是我复制了backtop组件代码封装成了自己需要的。
3、backTop:
- 通过传参‘target’拿到定位的父元素监听他的‘scrollTop’值,大于传参‘visibilityHeight’的之后就会使‘visible’为true,然后组件展示
- 固定在视口右下角是因为它本身是固定定位,并且在init方法中获取到的‘this.el’元素为body导致的,所以修改为自己需要固定的父元素即可。
最终解决办法代码
1、其实就是在box外层又套了一次main,高度和box一致,然后target继续监听box即可。
2、如果没有用组件的话,就是定位的父元素为main
<template>
<div class="main">
<div class="box">
<div class="list"></div>
</div>
<ceshi target=".box" :right="0">
搜索
</ceshi>
</div>
</template>
<script>
import ceshi from "./ceshi.vue";
export default {
name: "home_11",
components: {
ceshi
},
data() {
return {
}
},
};
</script>
<style>
.main {
height: 1000px;
position: relative;
border: 10px solid yellow;
}
.box {
width: 1000px;
height: 1000px;
border: 1px solid red;
position: relative;
overflow: auto;
margin: 0 auto;
}
.list {
width: 100%;
height: 2000px;
position: relative;
/* background: green; */
}
</style>
参考:
1、Element - The world's most popular Vue UI framework,饿了么官网
2、Vue ElementUI el-backtop 控件 | 黄威龙的笔记,大佬的组件代码讲解,包含源代码可直接复制使用