
>
java > TOPへ戻るとページ内リンクをスムーススクロール
TOPへ戻るとページ内リンクをスムーススクロール 2016年6月8日
Tag:
スクロールするとふゎっと現れるTOPへ戻るボタンと、ページ内リンクをスムーズにスクロールさせる
1.まずはjQueryの本体をダウンロードし、head~/headないに記述します。
2.下記のJavaScriptもheadないに書き込むか外部ファイルとして読み込みます
$(function() {
//ボタン表示スクリプト
var pagetop = $('.pagetop');
pagetop.css({'display': 'none'});
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
pagetop.fadeIn();
} else {
pagetop.fadeOut();
}
});
});
$(function() {
//移動するスクリプト
//ページ内リンク、#非表示。スムーズスクロール
$('a[href^="#"]').click(function(){
var speed = 800;
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;
});
});
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="smoothscroll.js"></script>
</head>
3.ページTOPへのボタンCSS
.pagetop {
position: fixed;
bottom: 100px;
right: 20px;
width: 50px;
height: 50px;
}
.pagetop a {
display: block;
width: 50px;
height: 50px;
border: solid 1px #22439c;
background: #FFFFFF;
color: #22439c;
font-size: 22px;
line-height: 2.2;
text-indent: 0.7em;
opacity:0.8;
}
.pagetop a:hover {
display: block;
width:50px;
height:50px;
color: #FFFFFF;
background: #4776AF;
border: solid 1px #22439c;
}