效果图如下,滚动条下拉的时候黑色的块TOP为0;固定显示:
代码如下:
复制代码 代码如下:
<!DOCTYPE html>
<html >
<head>
<title>jQuery实现页面滚动时层智能浮动定位</title>
<meta name="description" content="" />
<script type="text/javascript" src="http://jt.875.cn/js/jquery.js"></script>
<style type="text/css">
*{ margin:0; padding:0;}
.top{height:100px; background:#ccc;text-align:center; line-height:100px; font-size:40px;}
body { font:12px/1.8 Arial; color:#666; height:2000px;}
.float{width:200px; height:200px; border:1px solid #ffecb0; background-color:#000;position:absolute; right:10px; top:150px;}
</style>
</head>
<body>
<div class="top">导航啊导航啊导航</div>
<div class="float" id="float"></div>
<script type="text/javascript">
$.fn.smartFloat = function() {
var position = function(element) {
var top = element.position().top, pos = element.css("position");
$(window).scroll(function() {
var scrolls = $(this).scrollTop();
if (scrolls > top) {
if (window.XMLHttpRequest) {
element.css({
position: "fixed",
top: 0
});
} else {
element.css({
top: scrolls
});
}
}else {
element.css({
position: pos,
top: top
});
}
});
};
return $(this).each(function() {
position($(this));
});
};
//绑定
$("#float").smartFloat();
</script>
</div>
</body>
</html>