LoginSignup
14
15

More than 5 years have passed since last update.

ChromeでscrollTopを設定しようと思ったらハマった件

Posted at

エフェクトとかで何かとウィンドウのスクロール位置をセットすることは多いと思います。

何故かChromeで動かなくなり悩んだところ、
Webkit系でスクロール料の取得・設定に使用していたdocument.body.scrollTopが使えなくなってるのが原因らしく。
document.scrollingElement.scrollTopを呼べばよいみたい。

こんなコードを書いてたのですが動作せず。

setScrollTop(top) {
    // Webkit系であればdocument.body.scrollTopを呼ぶ。
    // それ以外はdocument.documentElement.scrollTopを。
    const tgt = (this.browser.isWebKit) ? document.body : document.documentElement;
    tgt.scrollTop = top;
}

こうしたら解決。

setScrollTop(top) {
    let tgt;
    if ('scrollingElement' in document) {
        tgt = document.scrollingElement;
    } else if (this.browser.isWebKit) {
        tgt = document.body;
    } else {
        tgt = document.documentElement;
    }
    tgt.scrollTop = top;
}

もうちょい頭良いコードにできると思いますがひとまず。

14
15
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
14
15