把下面代码放在html中就可以直接使用了
<style> .fl { width: 100px; height: 100px; position: fixed; } .fl img{ width: 100%; height: 100%; border-radius: 10%; } </style> <div class="fl" id="fl"> <img src="https://shx1024.top/uploads/admin/author_avatar/20210127/d244575d3237ee43e46bca336b43f7ad.jpg" alt=""> </div> <script> //获取需要浮动的div var fl = document.getElementById('fl'); //计算整个页面的宽高 var chroX = document.documentElement.clientWidth; var chroY = document.documentElement.clientHeight; //获取盒子位置,距离左边和顶部的距离 var offsetLeft = fl.offsetLeft; var offsetTop = fl.offsetTop; //setInterval停止标识 var timer = 0; //每次x轴和y轴的移动距离 var x = 1; var y = 1; //浏览器放大或缩小时重新获取页面宽高 window.onresize = function () { chroX = document.documentElement.clientWidth;//yemian整个的高宽 chroY = document.documentElement.clientHeight; } //浮窗移动的方法 function move() { offsetLeft += x; offsetTop += y; fl.style.left = offsetLeft + 'px'; fl.style.top = offsetTop + 'px'; } //浏览器加载完毕自动调用 window.onload = function () { timer = setInterval(function () { move(); if (offsetTop + 100 > chroY || offsetTop < 0) { y = -y; } if (offsetLeft + 100 > chroX || offsetLeft < 0) { x = -x; } }, 10) } //鼠标悬停在浮窗时停止移动 fl.onmouseenter = function () { clearInterval(timer) } //鼠标离开浮窗时继续移动 fl.onmouseleave = function () { window.onload(); } </script>
如果帮助到你,请赏杯奶茶喝~
- 本文链接: https://www.shx1024.top//index/article/details/article_id/104.shtml
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。