上下左右移动的悬浮框/气泡
1、示例图
2、组件代码
<template>
<div>
<div
v-if="show"
@mouseover="mouseover"
@mouseout="mouseout"
class="box"
:style="{ top: top + 'px', left: left + 'px' }"
>
<div>
<div style="text-align: right; padding-right: 5px">
<!-- element ui组件图标 -->
<i
class="el-icon-circle-close"
style="font-size: 18px; cursor: pointer"
@click="close"
></i>
</div>
<div style="padding: 10px">
<div>悬浮框测试</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "bubble",
data() {
return {
// 悬浮框显示
show: true,
// 移动速度
stepX: 1,
stepY: 1,
// 定时器
timer: null,
// 最大高度
maxTop: 0,
maxLeft: 0,
// 起始位置
top: 50,
left: 100
};
},
mounted() {
this.init();
},
beforeDestroy() {
// 销毁清除定时器
clearInterval(this.timer);
},
methods: {
/**
* 悬浮框移动
*/
init() {
this.maxTop = document.documentElement.clientHeight - 130 - 5;
this.maxLeft = document.documentElement.clientWidth - 200 - 5;
if (this.timer == null || this.timer == undefined) {
this.top = 50;
this.left = 100
this.timer = setInterval(() => {
this.move();
}, 20);
}
this.onresize();
},
/**
* 移动函数,触壁反弹
*/
move() {
if (this.top >= this.maxTop || this.top < 50) {
this.stepY = -this.stepY;
}
if (this.left >= this.maxLeft || this.left < 100) {
this.stepX = -this.stepX;
}
this.top += this.stepY;
this.left += this.stepX;
},
/**
* 鼠标移入
*/
mouseover() {
clearInterval(this.timer);
},
/**
* 鼠标移出
*/
mouseout() {
clearInterval(this.timer);
this.timer = setInterval(() => {
this.move();
}, 20);
},
/**
* 关闭悬浮框
*/
close() {
clearInterval(this.timer);
this.show = false;
},
/**
* 当窗口大小调整时重置悬浮框规则
*/
onresize() {
const that = this;
window.onresize = function () {
that.init();
};
},
},
};
</script>
<style scoped>
.box {
background: #3B99FB;
width: 200px;
height: 130px;
border-radius: 8px;
position: fixed;
text-align: left;
padding: 10px;
color: #ffffff;
top: 0;
left: 0;
z-index: 1000;
}
.box > div {
margin-top: 5px;
}
</style>
3、组件调用
<template>
<div>
<bubble></bubble>
</div>
</template>
<script>
import bubble from '@/xxx/bubble';
export default {
components:{
bubble
},
}
</script>