JS缓冲运动案例:右侧居中悬浮窗
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>JS小案例:右侧缓冲悬浮框</title> <style> body { height: 2000px; margin: 0px; } #div1 { 100px; height: 150px; background: red; position: absolute; right: 0; bottom:calc(50% - 75px); } </style> <script> //补充代码 </script> </head> <body> <div id='div1'></div> </body> </html>
参考案例
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>JS小案例:右侧缓冲悬浮框</title> <style> body { height: 2000px; margin: 0px; } #div1 { 100px; height: 150px; background: red; position: absolute; right: 0; bottom:calc(50% - 75px); } </style> <script> window.onscroll = function () { startMove(); } var timer = null; function startMove() { var oDiv = document.getElementById('div1'); clearInterval(timer); timer = setInterval(function () { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var iTarget = (document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + scrollTop; iTarget = Math.ceil(iTarget); var speed = (iTarget - oDiv.offsetTop) / 4; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (oDiv.offsetTop == iTarget) { clearInterval(timer); } else { oDiv.style.top = oDiv.offsetTop + speed + 'px'; } }, 30) } </script> </head> <body> <div id='div1'></div> </body> </html>