把下面代码放在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>
默认根据页面宽度自动计算rem和px的比例,把下面这段javascript贴进项目中便可以直接使用rem了
<script> (function (doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () { var clientWidth = docEl.clientWidth;//按照屏幕宽度计算,如果按照高度则改为clientHeight if (!clientWidth) return; docEl.style.fontSize = 100 * (clientWidth / 1920) + 'px'; }; if (!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window) </script>