8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

指定対象までぬるっとスクロールする

Posted at

そんなん楽勝だろって思ってた時代が僕にもありました。

jQueryが使えないとわかるまでは・・・

メモ

target_id は指定要素の id 属性の値を渡してあげてください。
var parent = document.getElementById(target_id); あたりをゴニョゴニョすれば id 属性以外の指定も可能です。

ぬるっとスクロール
function scroll(target_id) {
    var delay = 500;

    var start_time = new Date();
    var from = document.body.scrollTop || document.documentElement.scrollTop;
    var distance = getTop(target_id) - from - 10; // 10は遊び

    var animation_id = setInterval(function(){
        var time = new Date() - start_time;
        var current = Math.sin(Math.PI * 0.5 * (time / delay)) * distance + from;
        if (time > delay) {
            clearInterval(animation_id);
            current = from + distance;
        }
        document.body.scrollTop = current;
        document.documentElement.scrollTop = current;
    }, 5);
}

function getTop(target_id) {
    var top = 0;
    var parent = document.getElementById(target_id);
    while (parent) {
        top += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return top;
}
8
7
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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?