<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body { margin:0 auto; width:980px;height:1500px;}
#did { background:#eee;width:980px;height:25px;top:500px; position:absolute;}
#pid {text-align:center;}
</style>
</head><body>
<div id="did">
<div id="pid">bbbbbbb</div>
</div>
</body>
<script>
window.onscroll = function()
{
var did = document.getElementById("did")
var pid = document.getElementById("pid")
var dh = document.documentElement.scrollTop
if(dh>500)
{
did.style.top="0";
did.style.position="fixed";
}
else {
did.style.top="500";
did.style.position="absolute";
}
}
</script>
</html>
我要的效果是,滚动条把内容滚动到顶部的时候,就固定,当scrolltop 小于500的时候 又不固定到顶部了。。有点错呢,怎么完成呢。

解决方案 »

  1.   


    <script>
    window.onscroll = function(){
        var did = document.getElementById("did");
        //兼容ie,火狐,chrome
        var dh = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        if (dh > 500) {
            did.style.top = "0";
            did.style.position = "fixed";
        }
        else {
    did.style.top = "500px";
            did.style.position = "absolute";
        }
    }
    </script>
      

  2.   

    IE6 不支持 position="fixed";