LoginSignup
3
3

More than 3 years have passed since last update.

モバイルでのモーダル表示時の背景スクロール禁止処理

Last updated at Posted at 2020-08-04

以前よりhtml, body への overflow:hidden; はiOS Safari(webkit)では効かないため
主にjQueryで touchmove イベントに preventDefault(); で対応していたが

以前のコード
// スクロール無効
$(window).on('touchmove.noScroll', function(e) {
    e.preventDefault();
});  
// スクロール無効を解除
$(window).off('.noScroll');

iOS 11.3 Safari 11.1 及び Chrome 51 以降は addEventlistner の第3引数に { passive: false } を渡して対応する必要がある。

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
}, { passive: false });
ex
function scroll_control(e) {
    e.preventDefault();
}
function no_scroll(){
    document.addEventListener("touchmove", scroll_control, {passive: false});
}
function return_scroll(){
    document.removeEventListener('touchmove', scroll_control, {passive: false});
}

preventDefault() の付け外しは ex のように関数化しないとうまくいかなかった。
また'passive' オプションに未対応ブラウザのために Polyfill を書く必要がある。

polyfill
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
  var opts = Object.defineProperty({}, 'passive', {
    get: function() {
      supportsPassive = true;
    }
  });
  window.addEventListener("testPassive", null, opts);
  window.removeEventListener("testPassive", null, opts);
} catch (e) {}

// Use our detect's results. passive applied if supported, capture will be false either way.
elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false); 

elem fn の箇所と { passive: true } を適宜変更して使用

Browser

対応方法の参考リンク

Passive Event Listenersについての参考リンク

3
3
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
3
3