前回、こんなこと があり、2.10.0 で試しています。
lightbox2 のオプションには disableScrolling
があり、true
にすると Litebox が開いてる間はスクロールできなくなります。
オプションの参考:簡単に画像のポップアップ!「Lightbox」の実装方法
しかし、true
にしても、スマホではスクロールできるバグ?があります。
html
や body
タグに overflow: hidden
を指定するとスクロールできなくなります。
ただし、これはPCのみでスマホではスクロールできてしまいます。
そのため、JavaScriptで制御する必要があります。
preventDefault();
を使うスクロールを無効化できましたが、新しいブラウザでは効かないようです。
新しいブラウザで preventDefault()
を使いたいときは、passive:false
にする必要があります。
具体的に言うと addEventListener
の第3引数に {passive: false}
を指定します。
スクロール禁止・再開を関数化したのが下記です。
function scroll_control(event) {
event.preventDefault();
}
function no_scroll(){
document.addEventListener("mousewheel", scroll_control, {passive: false});
document.addEventListener("touchmove", scroll_control, {passive: false});
}
function return_scroll(){
document.removeEventListener("mousewheel", scroll_control, {passive: false});
document.removeEventListener('touchmove', scroll_control, {passive: false});
}
no_scroll()
を呼び出せばスクロールが禁止され、return_scroll()
を呼び出せばスクロール禁止してたのを再開できます。
これらを、litebox.js
(v2.10.0) に追記します。
追加箇所の抜粋です。
/*!
* Lightbox v2.10.0
* by Lokesh Dhakar
*
* More info:
* http://lokeshdhakar.com/projects/lightbox2/
*
* Copyright 2007, 2018 Lokesh Dhakar
* Released under the MIT license
* https://github.com/lokesh/lightbox2/blob/master/LICENSE
*
* @preserve
*/
// scroll control
function scroll_control(event) {
event.preventDefault();
}
function no_scroll(){
document.addEventListener("mousewheel", scroll_control, {passive: false});
document.addEventListener("touchmove", scroll_control, {passive: false});
}
function return_scroll(){
document.removeEventListener("mousewheel", scroll_control, {passive: false});
document.removeEventListener('touchmove', scroll_control, {passive: false});
}
// Show overlay and lightbox. If the image is part of a set, add siblings to album array.
Lightbox.prototype.start = function($link) {
no_scroll(); // この1行を追記しました。
var self = this;
var $window = $(window);
$window.on('resize', $.proxy(this.sizeOverlay, this));
$('select, object, embed').css({
visibility: 'hidden'
});
this.sizeOverlay();
this.album = [];
var imageNumber = 0;
function addToAlbum($link) {
self.album.push({
alt: $link.attr('data-alt'),
link: $link.attr('href'),
title: $link.attr('data-title') || $link.attr('title')
});
}
// Closing time. :-(
Lightbox.prototype.end = function() {
return_scroll(); // この1行を追記しました。
this.disableKeyboardNav();
$(window).off('resize', this.sizeOverlay);
this.$lightbox.fadeOut(this.options.fadeDuration);
this.$overlay.fadeOut(this.options.fadeDuration);
$('select, object, embed').css({
visibility: 'visible'
});
if (this.options.disableScrolling) {
$('html').removeClass('lb-disable-scrolling');
}
};