使用js或jq控制一个div,当滚动到页面顶部的时候固定在顶部,离开可继续滚动吗?

JavaScript010

使用js或jq控制一个div,当滚动到页面顶部的时候固定在顶部,离开可继续滚动吗?,第1张

代码:

•$(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"})

•}

•})

•})

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:0pxmargin:0px}.box{width:1000px

background:#cccmargin:0 autooverflow:hidden}.main{width:770pxheight:3000px。

background:#000float:left}.sub{width:220pxbackground:#FC6float:right}.。

4、sub01{width:220pxheight:100pxbackground:#0CCmargin-bottom:10px}.fixed

{width:220pxheight:300pxbackground:#F66font:normal 13px/30px \5FAE\8F6F\96C5\

9ED1text-align:centertop:10px}</style>。

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