javascriptでページ内リンクをぬるぬる動かす&ヘッダー固定
CSSでヘッダー部分をposition:fixedで固定すると、ページ内リンクがずれる。
正確に言うなら、ページ内リンクでページ上部に現れるはずのぶぶんが、ヘッダーの下に潜り込む。
ヘッダー固定だけならば、その下にコンテンツにヘッダー高さ分のmargin-topを設定すればすむが、ページ内リンクがことごとくずれる。
なので、それを回避する方法ついでにページ内リンクをぬるぬる動かした。
jqueryをリンクしてから、スクリプトをHTML部分に記述する。
<script type="text/javascript"> $(function () { // PageTopヘッダ分ずらす var headH = 130; // PageTop $('a[href^=#], area[href^=#]').not('a[href=#], area[href=#]').each(function () { jQuery.easing.quart = function (x, t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b;}; if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname && this.hash.replace(/#/, '')) { var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ($target) { var targetOffset = $target.offset().top - headH; $(this).click(function () { $('html, body').animate({ scrollTop: targetOffset }, 500, 'quart'); return false; }); } } }); if (location.hash) { var hash = location.hash; window.scroll(0, headH) $('a[href=' + hash + ']').click(); } }); </script>
で、CSSに記述を追加する。
#header { position: fixed!important; position: absolute; top: 0px; left: 0px; width: 100%; }
んで、#headerが高さ150pxだった場合、#headerの下、コンテンツ部分に以下のCSSを追加する。
#contents { margin-top: 150px; }
以上。
使いまわしがききそうなので、メモ。
参照:http://depthcode.com/2011/02/header-fixed.html