通过js监听滚动条事件来实现吸顶效果,该方法接受一个dom参数,返回 一个解绑事件的方法。
export function useCeiling(el) {
const parentNode = el.parentNode;
const parentTop = parentNode.offsetTop;
// 子组件距离父组件顶部的距离
const childTop = el.offsetTop - parentTop;
const childLeft = el.offsetLeft - parentNode.offsetLeft;
parentNode.addEventListener('scroll', bindEvent);
function bindEvent() {
if (this.scrollTop >= childTop) {
el.style.position = 'fixed';
el.style.top = `${parentTop}px`;
el.style.left = `${childLeft}px`;
el.style.zIndex = '9999';
} else {
el.style.position = 'static';
}
}
function unBind() {
parentNode.removeEventListener('scroll', bindEvent);
}
return {
unBind
}
}
在Vue中使用
<template>
<div class="frame" ref="frame">
<div style="height: 600px"></div>
<div class="child" ref="child"></div>
<div style="height: 1200px"></div>
</div>
</template>
<script>
import {useCeiling} from "@/views/js/UseVue";
let unbindObj = {};
export default {
name: "Ceiling",
methods: {
init() {
unbindObj = useCeiling(this.$refs.child);
}
},
mounted() {
this.init();
},
destroyed() {
const {unBind} = unbindObj;
typeof unBind === 'function' && unBind();
}
}
</script>
<style scoped>
.frame {
width: 100%;
height: 500px;
background-color: #42b983;
overflow: auto;
position: relative;
}
.child {
width: 100%;
height: 100px;
background-color: #fff;
}
</style>