前端实现图片在浏览器窗口随机移动
思路:
第一步,通过定位或则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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现