jQuery实现页面滚动时层智能浮动定位插件可以智能判断当滚动高度值大于顶部值就自动设置position: "fixed",top=0,这样层就一直处于顶部位置,反之刚设置回层原来的值,效果如下:
<!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=utf-8" />
<title>jQuery实现页面滚动时层智能浮动定位</title>
<meta name="author" content="创想工作室" />
<meta name="Copyright" content="www.22ba.com" />
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<style type="text/css">
*{ margin:0; padding:0;}
body { font:14px/1.8 Arial; color:#666; height:2000px; color:#00FF00;}
#top { background-color:#000000; text-align:center; padding-bottom:20px; padding-top:20px; }
.float{width:200px; height:200px; border:1px solid #ffecb0; background-color:#000;position:absolute; right:10px; top:150px;}
</style>
</head>
<body>
<div id="top">
<h2> JQuery让你的前端设计更精彩!</h2>
<div><a href="https://www.22ba.com/" target="_blank" style="color:#FFFFFF;" title="创想工作室">创想工作室</a></div>
</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>
</body>
</html>