问题描述
- JavScript页面悬浮框,菜鸟求助
-
我要在一个页面放2个悬浮框,悬浮框随页面的上下滚动有上下波动的效果,最终固定在同一位置,求助路过的大神!!<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body {height: 2000px;} #div1{ width: 100px; height: 150px; background: red; position: absolute;right: 0;bottom: 0; } #div2{ width: 200px;height: 200px;background:green; position: absolute; left: 0; top: 200px;} </style> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> <script> window.onscroll = function() { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动的距离 var oDiv = document.getElementById('div1'); oDiv.style.top = (document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + scrollTop + 'px'; startMove("div1", parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + scrollTop)); //计算滚动后的offsetTop var oDiv2 = document.getElementById('div2'); oDiv2.style.top = (document.documentElement.clientHeight - oDiv2.offsetHeight) / 2 + scrollTop + 'px'; startMove("div2", parseInt((document.documentElement.clientHeight - oDiv2.offsetHeight) / 2 + scrollTop)); }; function startMove(obj, target) { var timer = null; var oDiv = document.getElementById(obj); // 实现animate动作 clearInterval(timer); var iTarget = target; timer = setInterval(function() { var speed = (iTarget - oDiv.offsetTop) / 6; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if ((speed >= 0 && oDiv.offsetTop >= iTarget) || (speed <= 0 && oDiv.offsetTop <= iTarget)) { clearInterval(timer); } else { oDiv.style.top = oDiv.offsetTop + speed + 'px'; } }, 30); } </script></html>
解决方案
这个地方实质上是在运用setTimeout和setInterval时没有弄清楚二者的关系,这个地方你只要把setInterval更换成setTimeout即可解决问题;
setInterval是会持续执行,而setTimeout则仅执行一次,当然同样的,清除定时器指令也得更换为clearTimeout,你试试咯
时间: 2024-10-02 23:32:57