プレーンJavaScriptでページトップとアンカーリンク
今更だけど作る機会があったので保存。
プレーンでも offsetTop が使えることは知らなかった。
1 2 3 4 5 6 | <footer id="footer"> footer </footer> <div id="page-top">ページ上部へ</div> <div id="page-bottom">フッターへ</div> <script src="js/top_bottom.js"></script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /* to top and anchor Author: KEITA HIRAI URL: keitahirai.net */ var pageT = document.getElementById("page-top"), pageB = document.getElementById("page-bottom"), footerTop = document.getElementById("footer"); if (pageT != null) { pageT.addEventListener("click", function(e) { window.scrollTo(0, 0); e.stopPropagation(); }) } if (pageB != null) { pageB.addEventListener("click", function(e) { y = footerTop.offsetTop; window.scrollTo(0, y); e.stopPropagation(); }) } |
コメントを投稿する