<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #div1 {100px; height:100px; background:red; position: absolute; right:0;} </style> <script> window.onresize = window.onload = window.onscroll = function() { var oDiv = document.getElementById("div1"); var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var t = (document.documentElement.clientHeight - oDiv.offsetHeight)/2; oDiv.style.top = scrollTop + t + "px"; } </script> </head> <body style="height:2000px;"> <div id="div1"></div> </body> </html>
这种方法可以将div块实时显示到可视区中间,但是会出现闪烁问题。解决办法1:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #div1 {100px; height:100px; background:red; position: fixed; right:0; top:50%; margin-top:-50px;} </style> </head> <body style="height:2000px;"> <div id="div1"></div> </body> </html>
通过css布局解决闪烁问题,但是IE6并不支持fixed。可以使用动画滑入的方式解决IE6的固定定位问题,暂时不录入本文中。