jQuery 固定页脚

Avatar of Chris Coyier
Chris Coyier

通常,CSS 固定页脚 是最佳选择,因为它运行流畅且无需 JavaScript。如果所需的标记无法实现,则此 jQuery JavaScript 可能是另一种选择。

HTML

只需确保 #footer 是页面上最后一个可见元素。

<div id="footer">
    Sticky Footer
</div>

CSS

设置固定高度是最万无一失的方法。

#footer { height: 100px; }

jQuery

当窗口加载、滚动或调整大小时,它会测试页面内容是否短于窗口高度。如果是,则表示内容下方在窗口结束前存在空白区域,因此应将页脚重新定位到窗口底部。如果不是,则页脚可以保持其正常的静态定位。

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() { 
       
       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");
           
       positionFooter();
       
       function positionFooter() {
       
                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
       
               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }
               
       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)
               
});

演示

查看演示