实现效果如下:
需要设置的vue组件
<script>
export default {
// 页面创建钩子函数中添加事件监听
created() {
this.listenerFunction()
},
methods: {
// 事件监听 监听页面的 scroll 事件,回调方法为 handleScroll
listenerFunction(e) {
document.addEventListener('scroll', this.handleScroll, true)
},
// 编写滚动条事件
handleScroll() {
// 获取滚动条元素对象
let ele = document.getElementsByClassName('page-router-wrapper')[0]
// 获取需要固定的元素对象
let editorNav = document.getElementsByName('n_my_editor_nav')[0]
// 判断滚动条的高度(大于240,给固定元素添加 class)
if (ele.scrollTop > 240) {
editorNav.classList.add('suspension')
} else {
editorNav.classList.remove('suspension')
}
}
}
// 销毁事件监听
beforeDestroy() {
document.removeEventListener('scroll', this.listenerFunction)
}
}
</script>
css
<style>
.suspension{
top: 66px;
z-index: 99999;
position: fixed;
border-top: 1px solid #eee;
width: calc(100% - 248px);
}
</style>