原理:写一个让dom匀速移动的方法,然后用定时器每隔一定时间调用这个方法,然后鼠标放上去停止定时器,移除时继续定时器,下面直接上代码
<template>
<div>
<div id="thediv" ref="thediv" @mouseover="clearFdAd" @mouseout="starFdAd">我是浮动广告</div>
</div>
</template>
<script>
var interval
export default {
data() {
return {
xPos:300,
yPos:200,
step:1,
delay:8,
height:0,
Hoffset:0,
Woffset:0,
yon:0,
xon:0,
pause:true,
};
},
mounted() {
interval=setInterval(this.changePos,10)
},
methods: {
changePos()
{
let width=document.documentElement.clientWidth;
let height=document.documentElement.clientHeight;
this.Hoffset=this.$refs.thediv.offsetHeight;
this.Woffset=this.$refs.thediv.offsetWidth;
this.$refs.thediv.style.left=(this.xPos+document.body.scrollLeft+document.documentElement.scrollLeft)+"px";
this.$refs.thediv.style.top=(this.yPos+document.body.scrollTop+document.documentElement.scrollTop)+"px";
if(this.yon)
{
this.yPos=this.yPos+this.step;
}
else
{
this.yPos=this.yPos-this.step;
}
if(this.yPos<0)
{
this.yon=1;
this.yPos=0;
}
if(this.yPos>=(height-this.Hoffset))
{
this.yon=0;
this.yPos=(height - this.Hoffset);
}
if(this.xon)
{
this.xPos=this.xPos + this.step;
}
else
{
this.xPos=this.xPos - this.step;
}
if(this.xPos < 0)
{
this.xon = 1;
this.xPos = 0;
}
if(this.xPos >= (width - this.Woffset))
{
this.xon = 0;
this.xPos = (width - this.Woffset);
}
},
clearFdAd(){
clearInterval(interval)
},
starFdAd(){
interval=setInterval(this.changePos,10)
},
}
};
</script>
#thediv {
z-index: 100;
position: absolute;
top: 43px;
left: 2px;
height: 100px;
width: 100px;
background-color: red;
}
本文介绍了一种使用Vue实现的浮动广告DOM元素自动移动的方法。该方法通过设置定时器每隔一定时间调整DOM元素的位置,同时根据鼠标悬停状态启动或暂停移动效果。代码中详细展示了如何限制DOM元素在页面内的移动范围。
&spm=1001.2101.3001.5002&articleId=109350534&d=1&t=3&u=f49fc3cc32fb4c8493c8daa44aa6cf0a)
801

被折叠的 条评论
为什么被折叠?



