LPなどでよく使用するページ内リンクのスムーズスクロールの実装方法をまとめました。
メニューをそれぞれのアンカーリンクへスムーズスクロールさせ、ページ下部にあるページトップへテキストリンクは画面上部へスムーズスクロールさせます。
jQueryで、スムーズスクロールさせたいclassを複数指定しているので、他のサイトデザインにも応用が効きそうですね!
でもサイトはこちら
HTML
みどりへ、きいろへ、むらさきへをクリックすると、それぞれアンカーリンクを設定した箇所にスムーズスクロールします。
ページ下部のページトップテキストリンクをクリックすると、ページ上部へスムーズスクロールします。
<ul class="menu_list js-menu-list">
<li class="menu_item"><a href="#menu01">みどりへ<i class="fas fa-chevron-down"></i></a></li>
<li class="menu_item"><a href="#menu02">きいろへ<i class="fas fa-chevron-down"></i></a></li>
<li class="menu_item"><a href="#menu03">むらさきへ<i class="fas fa-chevron-down"></i></a></li>
</ul>
<div class="contents">
<div class="box" id="menu01">
<img src="https://cocotsubu.com/demo/demo01/images/01.jpg" alt="">
</div>
<div class="box" id="menu02">
<img src="https://cocotsubu.com/demo/demo01/images/02.jpg" alt="">
</div>
<div class="box" id="menu03">
<img src="https://cocotsubu.com/demo/demo01/images/03.jpg" alt="">
</div>
</div>
<p class="pagetop-text"><a class="pagetop-link js-pagetop-link" href="#pagetop">ページトップ<i class="fas fa-chevron-up"></i></a></p>
</div>
CSS
.wrapper{
display: block;
margin: 30px auto;
width: 80%;
}
.box img{
width: 100%;
vertical-align: bottom;
}
.menu_list{
display: flex;
margin-bottom: 20px;
justify-content: center;
}
.menu_item{
width: calc(100% / 3);
list-style: none;
text-align: center;
border-top: 1px solid #ccc;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
box-sizing: border-box;
}
.menu_item:first-of-type{
border-left: 1px solid #ccc;
}
.menu_item a{
display: inline-block;
width: 100%;
padding: 10px 0;
text-decoration: none;
font-size: 13px;
color: #333;
}
.menu_item i{
margin-left: 8px;
color: #ccc;
}
.pagetop-text{
display: block;
margin-top: 10px;
text-align: right;
}
.pagetop-link{
display: inline-block;
padding: 10px 0;
color: #333;
text-decoration: none;
}
.pagetop-link i{
margin-left: 5px;
color: #333;
}
jQuery
スムーズスクロールさせたいclassを複数指定しています。
今回はメニューの「.menu a」とページトップテキストリンクの「.pagetop-link」をスムーズスクロールさせます。
複数指定する場合は,(カンマ)で区切ってください。
$(function(){
$('.js-menu-list a, .js-pagetop-link').click(function(){
var speed = 500;
var href= $(this).attr("href");
var target = $(href == "#" || href == "" ? 'html' : href);
var position = target.offset().top;
$("html, body").animate({scrollTop:position}, speed, "swing");
return false;
});
});
おすすめのjQuery参考書はこちら!
posted with ヨメレバ
西畑一馬 アスキー・メディアワークス 2013年03月