3300.me

smooth_scroll (jQuery)

last update: 2016/07/16
<!doctype html>
<title>title</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script>
jQuery(function($){
  var hash;
  var pos;
  $('a[href ^= \'#\']').on('click', (el) => {
    hash = el.target.hash;
    if (hash === '#top') {
      pos = 0;
    } else {
      pos = $(hash).offset().top;
    }
    $('html, body').animate({scrollTop: pos}, 300, 'linear');
    return false;
  });
});

// $("a[href ^= '#']") ... #から始まるhrefを持つaタグ
// htmlで href="#top" にすればtopまでスクロール
// 300 ... スピード
// linear, swing ... 動きの種類
// return false ... preventDefaultの役割
</script>

<style>
html, body, ul, p {margin: 0; padding: 0; font-size: 14px;}
h1 {margin: 0;}
ul {position: fixed; top: 0; right: 0;}
li {list-style: none;}
a {display: block; width: 44px; height: 44px; border: #ddd 1px dotted; background: #fff; cursor: pointer;}
p {height: 400px;}
#a, #c, #e {background: #eee;}
</style>

<ul>
<li><a href="#top">top</a></li>
<li><a href="#a">a</a></li>
<li><a href="#b">b</a></li>
<li><a href="#c">c</a></li>
<li><a href="#d">d</a></li>
<li><a href="#e">e</a></li>
<li><a href="#f">f</a></li>
</ul>

<h1>smooth scroll</h1>
<p id="a">a</p>
<p id="b">b</p>
<p id="c">c</p>
<p id="d">d</p>
<p id="e">e</p>
<p id="f">f</p>

code_popup

sample (linear), sample (swing)