用vue写一个固定的广告栏
时间: 2023-05-23 22:01:44 浏览: 152
好的,这里是一个简单的使用 Vue 实现固定的广告栏的代码:
<template>
<div class="ad-wrapper" ref="adWrapper">
<img src="your-ad-image-url" alt="Ad" class="ad-img" />
</div>
</template>
<script>
export default {
data() {
return {
isFixed: false,
adWrapperHeight: 0,
initialTop: 0,
};
},
methods: {
handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop >= this.initialTop) {
this.isFixed = true;
} else {
this.isFixed = false;
}
},
},
mounted() {
this.adWrapperHeight = this.$refs.adWrapper.clientHeight;
this.initialTop = this.$refs.adWrapper.offsetTop;
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
};
</script>
<style scoped>
.ad-wrapper {
position: relative;
}
.ad-img {
width: 100%;
}
.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
</style>
这里我们需要监听 window 的 scroll 事件,来实现在滚动到一定位置时将广告栏固定在屏幕上方。在 mounted 钩子中,我们通过 ref 获取广告栏的高度和初始位置,然后添加一个 scroll 事件监听器并调用 handleScroll 函数。handleScroll 会根据当前的滚动位置计算是否需要将广告栏固定,如果需要,就会添加一个类名为 fixed 的样式,这个样式将广告栏固定在屏幕顶部。在 beforeDestroy 钩子中要记得删除 scroll 事件监听器,以避免内存泄漏问题。