三種方法實(shí)現(xiàn)智能浮動
方法一:
<script type="text/javascript">
$(function() {
var offset = $("#text-3").offset();
var topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
$("#text-3").stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
$("#text-3").stop().animate({
marginTop: 0
});
};
});
});
</script>
方法二:jQuery方式
$.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) { //如果滾動到頁面超出了當(dāng)前元素element的相對頁面頂部的高度
if (window.XMLHttpRequest) { //如果不是ie6
element.css({
position: "fixed",
top: 0
}).addClass("shadow");
} else { //如果是ie6
element.css({
top: scrolls
});
}
}else {
element.css({
position: pos,
top: top
}).removeClass("shadow")
}
});
};
return $(this).each(function() {
position($(this));
});
};
$(function(){
$(".wrapper-nav").smartFloat();
});
方法三:MooTools方式
var $smartFloat = function(elements) {
var position = function(element) {
var top = element.getPosition().y, pos = element.getStyle("position");
window.addEvent("scroll", function() {
var scrolls = this.getScroll().y;
if (scrolls > top) {
if (window.XMLHttpRequest) {
element.setStyles({
position: "fixed",
top: 0
});
} else {
element.setStyles({
top: scrolls
});
}
}else {
element.setStyles({
position: "absolute",
top: top
});
}
});
};
if ($type(elements) === "array") {
return elements.each(function(items) {
position(items);
});
} else if ($type(elements) === "element") {
position(elements);
}
};