Prevent absolute pos. footer div shake when scrolling
position:fixed
, this tiny plugin was a crossbrowser experiment to set an absolute
positioned element to the bottom of the page.
And it works. (IE6,7,8 / MOZ / Saf, Mob.Safari533.1 / O / ... ) Almost.
The 'only' problem is that when the page is scrolled --> the div shakes.
Do I need to bind to the .scroll() event some setInterval() or setTimeout() or something?
Any ide开发者_如何学Goas? Any suggestion? Thanks in advance!
The plugin:
(function($) {
$.fn.jFooter = function() {
var footer = this;
var fooH = footer.outerHeight();
function setFooPos() {
winH = $(window).height();
winS = $(window).scrollTop();
tot = (winH - fooH)+winS;
footer.css({
position: 'absolute',
top: tot + 'px'
});
}
// a div to compensate the scroll start:
$('body').append('<div id="fC" style="position:relative;height:'+ fooH +'px;width:100%;clear:both;"/>');
setFooPos();
$(window).bind('scroll resize',function () {
setFooPos();
});
};
})(jQuery);
I'm pretty sure that the shake is unavoidable. Since you have to base the top on the scrollTop, the DOM has to trigger the event, the javascript engine has to parse the javascript, and then the DOM is updated.
The shake is the delay of the DOM being updated, and the whole reason that position:fixed
exists.
As far as I'm aware, the reason position:fixed is smooth is because a position:fixed element does not have to be redrawn, or at least re-rendered when the page is scrolled. The reason this jumps is because you're redrawing the screen more than once, once for the scroll, and once for the position update.
Since it is a much better and easier solution, I would recommend detecting position:fixed
support and using that if available. If not available, add a throttled delay to have the footer reposition when the user stops or pauses scrolling. It's not pretty, but it's better than the shakiness (which can't be avoided, afaik):
$(window).bind('scroll resize',function () {
$.throttle( 500, setFooPos );
});
精彩评论