LoginSignup
6
5

More than 5 years have passed since last update.

AngularJS + zepto.js でスムーススクロール

Posted at

スムーススクロールのためにわざわざjQueryを入れたくなかったのでメモ。

function scroll() {
      //第一引数にスクロールする位置  第二引数は速度
      $('body').scrollTo(0, 400);
    }

    // zeptoへの拡張(๑•̀ㅂ•́)و✧
    $.fn.scrollTo = function(scrollHeight ,duration) {
      var $el = this;
      var el  = $el[0];
      var startPosition = el.scrollTop || document.documentElement.scrollTop;
      var delta = scrollHeight - startPosition;

      var startTime = Date.now();

      function scroll() {
        var fraction = Math.min(1, (Date.now() - startTime) / duration);

        el.scrollTop = delta * fraction + startPosition;
        // IE対策_:(´ཀ`」 ∠):_
        if(!el.scrollTop) {
          document.documentElement.scrollTop = delta * fraction + startPosition;
        }

        if(fraction < 1) {
          setTimeout(scroll, 10);
        }
      }
      scroll();
    };

やってることとしては、zeptoの拡張なんだけど。。
こんな感じでいいのかな…?
(IE対策周りが自信ない。。)

AngularJSのdirectiveにした例がこちら
https://github.com/keyiiiii/smooth-scroll-directive/blob/master/to-top-directive.js

scrollToの引数は変数にするなり適宜かえてもらえればと。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5