简易实现浮动效果的首要因素是:获取滚动条距离浏览器顶部的距离,下面直接贴代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js实现div效果悬浮</title> <style type="text/css"> #parentDIV { height: 2000px; } #suspensionBox { width: 230px; height: 50px; border: 1.5px solid red; text-align: center; line-height: 50px; border-radius: 5px; } .scrollTop{ position:fixed; top:100px; } </style> <script type="text/javascript"> window.onscroll=function(){ var t = document.documentElement.scrollTop||document.body.scrollTop; var suspensionBox = document.getElementById("suspensionBox"); suspensionBox.className = "scrollTop"; } </script> </head> <body> <div id="parentDIV"> <div id="suspensionBox">我要在中间呀,上上下下呀</div> </div> </body> </html>
是不是超级简单,是不是超级爽 哈哈哈~ (沧海一声笑, 滔滔两岸潮~)