「drawer.jsというjQueryライブラリはあるようですが今回それは使わずに、HTML, CSS, jQueryをゼロから書いて実装したので
備忘録として記事に残します。
Contents
jQueryを読み込むためのCDN
<script
src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"></script>
jQueryを書く(コピペ)する場所
いろいろ調べると、<head>内でも<body>ないでもいいようですが、遅延などを避けるためにも特別な事情がなければ<body>内が好ましいようです。
また注意点としては、jQueryのプログラムよりも先に(前に)読み込ませたほうがよいらしい。
つまり、
<body>
<!-- CDNを読み込ませる -->
<script
src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"></script>
<!-- ここまでCDN -->
<!-- ここからjQueryのプログラム -->
<script>
$(function(){
$('')...........
});
</script>
<!--jQueryのプログラムはここまで -->
</body>
<footer>
</footer>
といった感じ。
ドロワーメニューの書き方
今回は簡単に、3つのナビのひとつ「CONTACT」をドロワーメニューにすると仮定。
HTML + jQuery
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./css/s.css" />
</head>
<body>
<ul>
<li>HOME</li>
<li>ABOUT</li>
<li class="drawer">
WORK
<ul class="drawer-list">
<li><a href="">gallery</a></li>
<li><a href="">reputation</a></li>
<li><a href="">example</a></li>
</ul>
</li>
</ul>
<script
src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"
></script>
<script>
$(".drawer").click(function () {
$(".drawer-list").slideToggle();
});
</script>
</body>
</html>
CSS
.drawer{
position: relative;
}
.drawer-list{
position: absolute;
}
CSSは「position: relative;」と「position: absolute;」さえ抑えていればOKです!
トップへ戻るボタン
HTML
<button class="toppage" id="page-top"><span class="allow"></span></button>
jQuery(上のHTMLに追加すればOK)
$(function () {
$("#top-go-bottom").click(function () {
$("html,body").animate({ scrollTop: 0 }, 300);
});
$(window).scroll(function () {
if ($(window).scrollTop() > 1) {
$("#top-go-bottom").fadeIn(300).css("display", "flex");
} else {
$("#top-go-bottom").fadeOut(300);
}
});
});
CSS
.toppage {
position: fixed;
right: 100px;
bottom: 100px;
width: 100px;
height: 100px;
background-color: aquamarine;
border-radius: 900px;
border: #fff;
justify-content: center;
align-items: center;
display: none;
}
.allow {
display: block;
width: 20px;
height: 20px;
border-top: 3px solid #000;
border-right: 3px solid #000;
transform: rotate(-45deg);
}
ここでのPOINTは矢印borderで表現しているところと、jQueryでCSSメソッドを指定することで、そこで「display flex」を読み込ませているという点。
興味がある方は実装してみてください。