固定在网页顶部DIV层不跟随滚动条滑动

 

 体验效果:http://hovertree.com/texiao/jquery/25/


最近浏览网页时看到一个比较不错的做法,就是网页的某一块在随浏览器滚动快要消失的时候会浮动在页面上,页面还可以继续往上翻滚,但比较突出的那一块一直贴在浏览器的顶部,比如顶部导航条就可以用这种效果,何问起自我感觉这种效果还是比较贴心的,于是乎自己钻研了下,也写了这样一种效果,现在将代码贴在下面和大家分享。

完整代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery元素滚动到顶部固定 - 何问起</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base target="_blank" />
<script type="text/javascript" src="http://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<style>
body {
margin: 0px;
font-family: Arial;
}

a {
color: blue;
}
</style>
</head>
<body>
<div style="text-align:center;width:100%;margin:0px auto;">
<h1>何问起</h1>
jQuery元素滚动到顶部固定 <br />固定在网页顶部跟随滚动条滑动而滑动的DIV层<br />请滚动页面...<br />
<a href="http://hovertree.com/texiao/yestop/">Yestop</a> <a href="http://hovertree.com/h/bjaf/hoverclock.htm">HoverClock</a> <a href="http://hovertree.com">首页</a>
<a href="http://hovertree.com/texiao/">特效</a>
<a href="http://hovertree.com/h/bjaf/jqguding.htm">原文</a>
</div>
<div style="height: 360px;background-color: #66FF66;text-align:center;">
</div>
<div style="width:100%;text-align:center;height:200px;background-color:skyblue" id="divhovertree">&copy; hovertree.com</div>
<div style="height: 200px; visibility: visible; background-color: Olive">
</div><div style="height:200px;background-color:burlywood"></div><div style="height:200px;background-color:darkorchid"></div>
<div style="height: 200px; visibility: visible; background-color:gray">
</div>
<div style="height:200px;background-color:blue"></div>
<div style="height:200px;background-color:red"></div>
<div style="height:200px;background-color:yellow"></div>
<div style="height:200px;background-color:yellowgreen"></div>
<div style="height:800px;background-color:white"></div>
<script type="text/javascript">
/*
*滚动条滑动,位置不变的DIV层
*div_id:DIV的ID属性值,必填参数
*offsetTop:滚动条滑动时DIV层距顶部的高度,可选参数
*/
function fixDiv(div_id, offsetTop) {
var Obj = $('#' + div_id);
//判断元素是否存在 何问起
if (Obj.length != 1) { return false; }

var offsetTop = arguments[1] ? arguments[1] : 0;
var ObjTop = Obj.offset().top;


$(window).scroll(function () {
if ($(window).scrollTop() <= ObjTop) {
Obj.css({
'position': 'relative',
"top": 0
});
} else {
Obj.css({
'position': 'fixed',
'top': 0 + offsetTop + 'px',
'z-index': 10
});
}
});
}
fixDiv('divhovertree', 5);//顶端浮动并于顶端保持5px的间距
</script>
</body>
</html>

 更多特效: http://ini.iteye.com/blog/2165698 

你可能感兴趣的:(html,jquery,Web,css,javascirpt)