ameeeee
9/28/2019 - 1:06 PM

jquery : トップへ戻る、ページ内リンク

jquery : トップへ戻る、ページ内リンク

<div class="inner">
	<header>
		<a href="#1">#1</a>
		<a href="#2">#2</a>
	</header>
	<div id="1" class="item01">
		item01
	</div>
	<div class="go-to-top">トップへ戻る</div>
	<div id="2" class="item02">
		item02
	</div>
	<div class="go-to-top">トップへ戻る</div>
</div>
	

jquery : トップへ戻る、ページ内リンク

A Pen by anonie on CodePen.

License.

$(function(){
	// トップへ戻る
  $('.go-to-top').click(function(){
    $('html,body').animate({ 
      'scrollTop': 0 
    }, 'slow');
  });
	
	// ページ内リンク
  $('header a').click(function(){
    var id = $(this).attr('href');
    var position = $(id).offset().top;
    $('html, body').animate({
      'scrollTop': position
    }, 500);
  });

	
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
*, *::before, *::after {  box-sizing: border-box; }
body { background: #eee; }
.flex { display: flex; }
.inner {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
}
.inner { background: #fff; margin: 3rem auto; padding: 3rem 0;} // 視認性用

.item01 {  // 視認性用
	border: 3px solid #aaa;
	height: 500px;
}
.item02 {  // 視認性用
	border: 3px solid #ccc;
	height: 500px;
}
$breakpoints: (
	sp: "only screen and (max-width: 559px)",
	tb: "only screen and (max-width: 959px)",
	pc: "only screen and (min-width: 960px)"
);
@mixin media($breakpoint) {
  @media #{map-get($breakpoints, $breakpoint)} {
    @content;
  }
}
.pc {
  @include media(sp) {
    display: none !important;
  }
}
.sp {
  @include media(pc) {
    display: none !important;
  }
}
/// 以下モジュール ---------------------------------