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

思路:

第一步,通过定位或则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 @   轩悦  阅读(466)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示