前端实现图片在浏览器窗口随机移动

思路:

第一步,通过定位或则margin实现图片的移动;

第二步,判断图片碰到浏览器边框后进行折返;

第三步,实时获取浏览器边框大小设置定时任务;

html代码:

<template>
  <div class="email-container">
    <img id="email-img" src="../assets/email-img.png" >
  </div>
</template>

css代码

* {
  margin: 0;
  padding: 0;
}
body {
  overflow: hidden;
}
.email-container {
  display: flex;
  background: url('../assets/email_bg.jpg') center no-repeat;
  background-color: rgba(181, 48, 52, 1);
  background-size: cover;
  text-align: center;
  vertical-align: middle;
  text-align: center;
}
#email-img {
  margin: auto;
  width: 20%;
  cursor: pointer;
}

js实现

<script>
export default {
  data() {
    return {
      showEmail: true,
      leftMargin: 0,
      topMargin: 0,
      topNum: 0,
      leftNum: 0,
      topFlag: 0,
      leftFlag: 0,
      img: '',
    }
  },

  mounted() {
    this.img = document.getElementById('email-img')
    this.leftNum = (document.documentElement.clientWidth - this.img.clientWidth) / 2
    this.topNum = (document.documentElement.clientHeight - this.img.clientHeight) / 2
    this.imgMove()
  },
  methods: {
    imgMove() {
      this.leftMargin = document.documentElement.clientWidth - this.img.clientWidth
      this.topMargin = document.documentElement.clientHeight - this.img.clientHeight
      //判断让其上下移动
      if (this.topNum <= 0) {
        this.topFlag = true
        this.topNum = 0
      }
      if (this.topNum >= this.topMargin) {
        this.topFlag = false
        this.topNum = this.topMargin
      }
      this.topNum = this.topFlag ? (this.topNum += 1) : (this.topNum -= 1)
      //判断让其左右移动
      if (this.leftNum <= 0) {
        this.leftFlag = true
        this.leftNum = 0
      }
      if (this.leftNum >= this.leftMargin) {
        this.leftFlag = false
        this.leftNum = this.leftMargin
      }
      this.leftNum = this.leftFlag ? (this.leftNum += 1) : (this.leftNum -= 1)

      this.img.style.marginTop = this.topNum + 'px'
      this.img.style.marginLeft = this.leftNum + 'px'
      let move = setTimeout(this.imgMove, 15)
      if (!this.showEmail) {
        clearTimeout(move)
      }
    },
  },
}
</script>

 

posted @ 2022-06-21 14:47  轩悦  阅读(425)  评论(0编辑  收藏  举报