vue实现浮动广告(浏览器范围内匀速移动)

本文介绍了一种使用Vue实现的浮动广告DOM元素自动移动的方法。该方法通过设置定时器每隔一定时间调整DOM元素的位置,同时根据鼠标悬停状态启动或暂停移动效果。代码中详细展示了如何限制DOM元素在页面内的移动范围。

原理:写一个让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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值