求助:如果使用js\jq 控制一个div 当滚动到页面顶部的时候固定在顶部,离开可继续滚动

求助:如果使用js\jq 控制一个div 当滚动到页面顶部的时候固定在顶部,离开可继续滚动【希望能兼容所有浏览器】

1、新建html文档。

2、书写hmtl代码<div class="box">    <!--代码开始--><div class="main"></div><div class="sub"><div class="sub01"></div><div class="sub01"></div><div class="fixed">我是固定的哟</div></div><!--代码结束--></div>。

3、书写css代码。<style type="text/css">**{padding:0px;margin:0px;}.box{width:1000px;

;background:#ccc;margin:0 auto;overflow:hidden;}.main{width:770px;height:3000px;。

;background:#000;float:left;}.sub{width:220px;background:#FC6;float:right;}.。

4、sub01{width:220px;height:100px;background:#0CC;margin-bottom:10px;}.fixed

{width:220px;height:300px;background:#F66;font:normal 13px/30px \5FAE\8F6F\96C5\

9ED1;text-align:center;top:10px;}</style>。

5、书写并添加js代码。<script src="js/jquery.js"></script>。这就完成了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-28
代码:
•$(function(){

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

•var navH = $(".nav").offset().top;

•//滚动条事件

•$(window).scroll(function(){

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

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

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

•if(scroH>=navH){

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

•}else if(scroH<navH){

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

•}

•})

•})本回答被网友采纳
第2个回答  2012-11-29
怎么发给你?