vue实现漂浮广告
实现漂浮广告的基本思路
在Vue中实现漂浮广告可以通过动态样式绑定和定时器控制广告元素的位置。核心是利用CSS的position: fixed或absolute定位,结合JavaScript修改top/left等属性实现移动效果。
基础实现代码示例
<template>
<div
class="floating-ad"
:style="{
left: position.x + 'px',
top: position.y + 'px',
}"
@mouseenter="pauseMove"
@mouseleave="resumeMove"
>
<!-- 广告内容 -->
<img src="ad-image.png" alt="广告">
</div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
direction: { x: 1, y: 1 },
speed: 2,
moveInterval: null
}
},
mounted() {
this.startMove();
},
beforeDestroy() {
clearInterval(this.moveInterval);
},
methods: {
startMove() {
this.moveInterval = setInterval(() => {
this.position.x += this.direction.x * this.speed;
this.position.y += this.direction.y * this.speed;
// 边界检测
if (this.position.x <= 0 || this.position.x >= window.innerWidth - 100) {
this.direction.x *= -1;
}
if (this.position.y <= 0 || this.position.y >= window.innerHeight - 100) {
this.direction.y *= -1;
}
}, 16);
},
pauseMove() {
clearInterval(this.moveInterval);
},
resumeMove() {
this.startMove();
}
}
}
</script>
<style>
.floating-ad {
position: fixed;
width: 100px;
height: 100px;
cursor: pointer;
z-index: 9999;
}
</style>
优化方向
边界限制增强
通过window.innerWidth和window.innerHeight动态获取可视区域尺寸,确保广告不会超出屏幕范围。

性能优化
使用requestAnimationFrame替代setInterval可获得更流畅的动画效果:
move() {
this.position.x += this.direction.x * this.speed;
this.position.y += this.direction.y * this.speed;
// 边界检测逻辑
if (this.position.x <= 0 || this.position.x >= window.innerWidth - 100) {
this.direction.x *= -1;
}
if (this.position.y <= 0 || this.position.y >= window.innerHeight - 100) {
this.direction.y *= -1;
}
this.animationId = requestAnimationFrame(this.move);
}
关闭功能 添加关闭按钮提升用户体验:

<div class="floating-ad">
<span class="close-btn" @click="closeAd">×</span>
<!-- 广告内容 -->
</div>
<style>
.close-btn {
position: absolute;
right: 5px;
top: 0;
cursor: pointer;
}
</style>
移动端适配
针对移动设备需要添加触摸事件支持:
@touchstart="pauseMove"
@touchend="resumeMove"
并调整广告尺寸:
@media (max-width: 768px) {
.floating-ad {
width: 80px;
height: 80px;
}
}






