スマホサイトとかで流行りのフッター固定バナー的なやつがスクロールしてるうちにフッターにぶち当たったときの処理。
display:flex;状態だとフッターの上に被っちゃうので、被らないようにします。
まずHTML。ちなみにソースの中の「height」は適宜変えてください。
あと、フッターの上で固定させたい要素は、固定させたい場所に書いてください。(position指定無し状態での単純な位置)
↓だとちゃんとfooterの上に書いて、positionとか指定しない場合ちゃんとfooterの上にぴちっと出ると思います。
それと、headerとかcontentとかの構成は適当です。何が大事かって、固定したい要素の#sticky_footerの器をしっかり作るのが大事なのです。
何故なのかは後述します。
<header>
ヘッダ~
</header>
<div id="content">
こんてんつ!
</div>
<div style="height:50px;width:100%;">
<footer id="sticky_footer">
#sticky_footerを固定したい!
</footer>
</div>
<footer id="main_footer">
フッタ~
</footer>
CSSです。ここでどういう要素か定義しておきます。主に装飾。
footer.sticky_footer{
background-color: #ff00ff;
height:50px;
width: 100%;
color:#fff;
text-align: center;
line-height: 50px;
}
JSです。クラス名とかは適宜変えてください。
jQuery(window).on("scroll", function() {
documentHeight = jQuery(document).height();
scrollPosition = jQuery(this).height() + jQuery(this).scrollTop();
footerHeight = jQuery("#site_footer").outerHeight();
if (documentHeight - scrollPosition <= footerHeight) {
jQuery("#sticky_footer").css({
position: "static",
bottom: "auto"
});
} else {
jQuery("#sticky_footer").css({
position: "fixed",
bottom: 0
});
}
});
こんな感じです。
あと上で言ってたことですが、ちゃんと固定したい要素と同じ高さの器を作っておかないと、いざ要素が固定された時に新要素が入ってきた!となってサイトの高さが変わってスクロールバーがグニュっと動いてフッターがガクッと落ちた感じになっちゃいますね。そういうための対策です。
これはあまり他のサイトも書いてなくて困りました。