js 网页代码 div随滚动条 移动到浏览器顶部 固定的问题

<!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=gb2312" />
<title></title>
<script src="jquery-1.11.1.js"></script>
<script type="text/javascript">
//$(document).ready(function(){

$(function(){

//获取要定位元素距离浏览器顶部的距离

var navH = $(".nb").offset().top;

//滚动条事件

$(window).scroll(function(){

//获取滚动条的滑动距离

var scroH = $(this).scrollTop();

//滚动条的滑动距离大于等于定位元素距离浏览器顶部的距离,就固定,反之就不固定

if(scroH>=navH){

$(".nb").css({"position":"fixed","top":0});

}else if(scroH<navH){

$(".nb").css({"position":"static"});

}

})

})
//})
</script>

</head>

<body>
<div style="background:#003366;height:500px;">空div</div>

<div style="height:500px;width:200px;background:purple">
<div class="nb" style="height:100px;width:100px;background:#9966FF">移动到顶部固定不变</div>
</div>

<div style="background:#ff0000;height:1500px;">空div</div>
<div style="background:#ccc;height:1500px;">空div</div>
</body>
</html>

网上 看到的代码 我想让蓝色的代码块底部 在到紫色代码块底部的时候 停止固定要怎么办呢?
还有 我要是 想要设置2个 div 随动块 一上一下 要怎么设置呢?

//html
<body>  
<div style="background:#003366;height:500px;">空div</div> 
<div  class="purple" style="height:500px;width:200px;background:purple">
<div class="nb" style="height:100px;width:100px;background:#9966FF">移动到顶部固定不变</div>  
</div>
<div class="red" style="background:#ff0000;height:1500px;">空div</div>  
<div style="background:#ccc;height:1500px;">空div</div>  
<div class="nb2" style="height:100px;width:100px;background:gray;">移动到底部固定不变</div> 
</body> 
//js
$(function(){  
    //获取要定位元素距离浏览器顶部的距离 
    var navH = $(".nb").offset().top;  
    var navH2 = $(".nb2").offset().top; 
    var Pur= $(".purple").offset().top;     //紫色块
    var Red= $(".red").offset().top;     //红色块
    //滚动条事件  
    $(window).scroll(function(){  
      //获取滚动条的滑动距离  
      var scroH = $(this).scrollTop();  
      //滚动条的滑动距离大于等于定位元素距离浏览器顶部的距离,就固定,反之就不固定  
      if(scroH>=navH){  
        $(".nb").css({"position":"fixed","top":0});  
      }else if(scroH<navH){  
        $(".nb").css({"position":"static"});    
      }
      if(scroH <= navH2){  
        $(".nb2").css({"position":"fixed","bottom":"15px","right":"15px"});  
      }else if(scroH<navH){  
        $(".nb2").css({"position":"static"});    
      }
      if(scroH >= Pur && scroH <= Red){
        $(".nb").css({"position":"static"});  //在紫色块的时候不固定
        $(".nb2").css({"position":"static"});  //在紫色块的时候不固定
      }
    })  
  })

追问

虽然很感谢你的帮助 不过完全不是我要的效果……
我的意思是说“移动到顶部固定不变”这个模块 只能在 紫色里显示……
完全反了 我看看能看懂你的代码不……

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-01
你是指停止固定还是固定?因为你现在没有固定在页面顶部啊。
这个问题可以用js判断,判断一下滑动到的位置决定。
关于这个一上一下的,我记得有一个插件可以实现,你可以查查,运气好能找到。找不到自己做吧,js控制位置方向还不错。