多くのウェブサイトで当たり前のように設置されており、ユーザビリティーの向上につながるページトップスクロールのコードを掲載します。様々な制作方法があると思いますが、今回紹介する方法にはjQueryを用います。動きがスムーズで簡単に設置できますのでコピーペーストでご自由にお使いください。
[html]
<div id="top_scroll">
<a href="#" id="page-top1"><img src="images/example_top.png" alt="ページトップスクロール"></a>
</div>
[/html]
[css]
#top_scroll{
position: relative;
z-index: 100;
margin: 0;
padding: 0;
}
#page-top1{
display: block;
position: fixed;
z-index: 9999;
bottom: -250px;
right: 10px;
width: 35px;
height: 35px;
padding: 0;
color: #222;
text-align: center;
text-decoration: none;
transition: 1s;
-webkit-transition: 1s;
}
#page-top1:hover{
background: ;
transform: translateY(-10px);
}
#top_scroll:hover{
background: #fff;
}
[/css]
[html]
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
var pageTop1 = $("#page-top1");
pageTop1.click(function () {
$(‘body, html’).animate({ scrollTop: 0 }, 500);
return false;
});
$(window).scroll(function () {
if($(this).scrollTop() >= 200) {
pageTop1.css( "bottom", "30px" );
} else {
pageTop1.css( "bottom", "-85px" );
}
});
});
</script>
[/html]
デモは、マウスオーバー時にボタンがアニメーションで動きます。上記コードを参考にカスタムしていますので、ご確認頂けると嬉しいです。
もう1つ超シンプルなスクロールトップをご紹介致します。正直こちらのほうが実装の難易度は低いと思います。
[html]
<div id="stop" class="scrollTop">
<a href="">Top</a>
</div>
[/html]
[css]
.scrollTop {
position: fixed;
right: 20px;
bottom: 30px;
opacity: 0;
transition: all 0.4s ease-in-out 0s;
}
.scrollTop a {
font-size: 18px;
color: #fff;
background: #1856C9;
padding: 20px;
}
.scrollTop a:hover{
background: #44CAFF;
}
[/css]
[html]
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// declare variable
var scrollTop = $(".scrollTop");
$(window).scroll(function() {
// declare variable
var topPos = $(this).scrollTop();
// if user scrolls down – show scroll to top button
if (topPos > 100) {
$(scrollTop).css("opacity", "1");
} else {
$(scrollTop).css("opacity", "0");
}
}); // scroll END
//Click event to scroll to top
$(scrollTop).click(function() {
$(‘html, body’).animate({
scrollTop: 0
}, 800);
return false;
}); // click() scroll top EMD
}); // ready() END
</script>
[/html]
デモは、マウスオーバー時にボタンがアニメーションで動きます。上記コードを参考にカスタムしていますので、ご確認頂けると嬉しいです。
この記事を掲載しながら、スクロールトップを始めて実装した時の事を思い出しました。無駄にボタンを押してスルスル上に移動する画面を見るだけで楽しくなっていました。