因为要做一个页面滚动时元素浮动定位,就在网上找到了这篇博客:http://www.helloweba.com/view-blog-194.html
博主写的很好,我截取了其中我需要的函数,修改了一点,存在这里了。
/*jQuery实现页面滚动时元素智能定位*/
$.fn.smartFloat = function() {
var position = function(element) {
var top = element.position().top; //当前元素对象element距离浏览器上边缘的距离
var pos = element.css("position"); //当前元素距离页面document顶部的距离
$(window).scroll(function() { //侦听滚动时
var scrolls = $(this).scrollTop();
if (scrolls > top) { //如果滚动到页面超出了当前元素element的相对页面顶部的高度
if (window.XMLHttpRequest) { //如果不是ie6
element.css({ //设置css
position: "fixed", //固定定位,即不再跟随滚动
top: 0 ,//距离页面顶部为0
"background":"red"
});
} else { //如果是ie6
element.css({
top: scrolls //与页面顶部距离
});
}
}else {
element.css({ //如果当前元素element未滚动到浏览器上边缘,则使用默认样式
position: pos,
top: top,
background:"green"
});
}
});
};
return $(this).each(function() {
position($(this));
});
};
上面这段函数可以封装到js文件中调用,调用如下
$(function(){
$("#flo").smartFloat();
});