开发者社区 问答 正文

!javascript新手。

<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.getElementById("did").scrollTop
    if(dh>500)
    {
        did.style.top="0";
        did.style.position="fixed";
    }
    else {
        did.style.top="500";
        did.style.position="absolute";
         
     
    }
}
</script>
我要的效果是,滚动条把内容滚动到顶部的时候,就固定,当scrolltop 小于500的时候 又不固定到顶部了。。有点错呢,请指点。

展开
收起
a123456678 2016-07-15 14:46:03 1786 分享 版权
1 条回答
写回答
取消 提交回答
  • <!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>无标题文档</title>
    <style type="text/css">
    body{ padding:0; margin:0;}
    #main{width:800px; height:2000px; margin: 0 auto; background:#9CC; position:relative; }
    #other{clear:both; height:128px;}
    #box{width:560px; height:45px; background:#39C; margin:0 auto; position:absolute; top:128px;}
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
     $(function(){ 
      $(window).scroll(function(){
        
       boxY = $('#box').offset().top;
       $("#box").text(boxY);
       yy = $(this).scrollTop();
       xx = $(this).width();
       if ($(this).scrollTop() > 128) {
          
        $('#box').css({"position":"fixed",top:"0px"});
         
       } else {
         
        $('#box').css({"position":"absolute",top:"128px"});
         
       }
        
      })
      
      
     })
    </script>
    </head>
    <body>
    <div id="main">
     <div id="other"></div>
     <div id="box"></div>
    </div>
    </body>
    </html>
    2019-07-17 19:56:58
    赞同 展开评论
问答分类:
问答地址: