web-dev-qa-db-ja.com

一時的にスクロールを無効にするにはどうすればいいですか?

ScrollTo jQueryプラグインを使用していますが、Javascriptを使用してウィンドウ要素のスクロールを一時的に無効にすることがどういうわけか可能かどうかを知りたいですか。スクロールを無効にしたいのは、scrollToがアニメートしているときにスクロールすると、本当に見苦しいからです。

もちろん、アニメーションが停止したときに$("body").css("overflow", "hidden");を実行してからautoに戻すこともできますが、スクロールバーがまだ表示されているが非アクティブであれば、もっと良いでしょう。

391
Olivier Lalonde

scrollイベントはキャンセルできません。しかし、あなたはそれを取り消しこれらのインタラクションイベント:
マウススクロールに関連するタッチスクロールおよびボタン)。

[ 実用的なデモ ]

// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;  
}

function preventDefaultForScrollKeys(e) {
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
}

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  document.addEventListener('wheel', preventDefault, {passive: false}); // Disable scrolling in Chrome
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

function enableScroll() {
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    document.removeEventListener('wheel', preventDefault, {passive: false}); // Enable scrolling in Chrome
    window.onmousewheel = document.onmousewheel = null; 
    window.onwheel = null; 
    window.ontouchmove = null;  
    document.onkeydown = null;  
}

編集

この機能がChromeでも機能するようにdocument.addEventListener('wheel', preventDefault, {passive: false});を追加しました。

670
gblazex

本体にクラスを追加することで簡単にできます。

.stop-scrolling {
  height: 100%;
  overflow: hidden;
}

クラスを追加してから、IE、FF、Safari、およびChromeでテストされたスクロールを再度有効にする場合は削除します。

$('body').addClass('stop-scrolling')

モバイルデバイス の場合、touchmoveイベントを処理する必要があります。

$('body').bind('touchmove', function(e){e.preventDefault()})

スクロールを再度有効にするには、バインドを解除します。 iOS6とAndroid 2.3.3でテスト済み

$('body').unbind('touchmove')
397
hallodom

これを行うための本当に基本的な方法は次のとおりです。

window.onscroll = function () { window.scrollTo(0, 0); };

IE6ではちょっととんでもないですね。

50
sdleihssirhc

次の解決策は基本的なものですが純粋なJavaScriptです(jQueryなし):

function disableScrolling(){
    var x=window.scrollX;
    var y=window.scrollY;
    window.onscroll=function(){window.scrollTo(x, y);};
}

function enableScrolling(){
    window.onscroll=function(){};
}
29
Mohammad Anini

このソリューションは、スクロールを無効にしている間、現在のスクロール位置を維持します。ユーザーを一番上に移動させるものとは異なります。

これは galambalazsの回答 に基づいていますが、タッチデバイスをサポートしており、jqueryプラグインラッパーを持つ単一のオブジェクトとしてリファクタリングされています。

デモはこちら。

ここgithubに。

/**
 * $.disablescroll
 * Author: Josh Harrison - aloof.co
 *
 * Disables scroll events from mousewheels, touchmoves and keypresses.
 * Use while jQuery is animating the scroll position for a guaranteed super-smooth ride!
 */

;(function($) {

    "use strict";

    var instance, proto;

    function UserScrollDisabler($container, options) {
        // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
        // left: 37, up: 38, right: 39, down: 40
        this.opts = $.extend({
            handleKeys : true,
            scrollEventKeys : [32, 33, 34, 35, 36, 37, 38, 39, 40]
        }, options);

        this.$container = $container;
        this.$document = $(document);
        this.lockToScrollPos = [0, 0];

        this.disable();
    }

    proto = UserScrollDisabler.prototype;

    proto.disable = function() {
        var t = this;

        t.lockToScrollPos = [
            t.$container.scrollLeft(),
            t.$container.scrollTop()
        ];

        t.$container.on(
            "mousewheel.disablescroll DOMMouseScroll.disablescroll touchmove.disablescroll",
            t._handleWheel
        );

        t.$container.on("scroll.disablescroll", function() {
            t._handleScrollbar.call(t);
        });

        if(t.opts.handleKeys) {
            t.$document.on("keydown.disablescroll", function(event) {
                t._handleKeydown.call(t, event);
            });
        }
    };

    proto.undo = function() {
        var t = this;
        t.$container.off(".disablescroll");
        if(t.opts.handleKeys) {
            t.$document.off(".disablescroll");
        }
    };

    proto._handleWheel = function(event) {
        event.preventDefault();
    };

    proto._handleScrollbar = function() {
        this.$container.scrollLeft(this.lockToScrollPos[0]);
        this.$container.scrollTop(this.lockToScrollPos[1]);
    };

    proto._handleKeydown = function(event) {
        for (var i = 0; i < this.opts.scrollEventKeys.length; i++) {
            if (event.keyCode === this.opts.scrollEventKeys[i]) {
                event.preventDefault();
                return;
            }
        }
    };


    // Plugin wrapper for object
    $.fn.disablescroll = function(method) {

        // If calling for the first time, instantiate the object and save
        // reference. The plugin can therefore only be instantiated once per
        // page. You can pass options object in through the method parameter.
        if( ! instance && (typeof method === "object" || ! method)) {
            instance = new UserScrollDisabler(this, method);
        }

        // Instance already created, and a method is being explicitly called,
        // e.g. .disablescroll('undo');
        else if(instance && instance[method]) {
            instance[method].call(instance);
        }

    };

    // Global access
    window.UserScrollDisabler = UserScrollDisabler;

})(jQuery);
24
Josh Harrison

古い記事に答えてすみませんが、私は解決策を探していて、この質問に出くわしました。

スクロールバーを表示するには、コンテナに100%の高さとoverflow-y: scrollのスタイルを設定するなど、この問題に対して多くの回避策があります。

私の場合はoverflow: hiddenをボディに追加しながら表示するスクロールバー付きのdivを作成しました。

function disableScroll() {
    document.getElementById('scrollbar').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

要素スクロールバーは以下のスタイルを持っていなければなりません:

overflow-y: scroll; top: 0; right: 0; display: none; height: 100%; position: fixed;

これは灰色のスクロールバーを示しています。将来の訪問者に役立つことを願います。

14
lisovaccaro

この問題の解決策を探していましたが、上記の解決策のいずれにも満足できなかったので( この回答を書いた時点では )、この解決策を思いついたのです。

_ css _

.scrollDisabled {   
    position: fixed;
    margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
    width: 100%;
}

_ js _

var y_offsetWhenScrollDisabled=0;

function disableScrollOnBody(){
    y_offsetWhenScrollDisabled= $(window).scrollTop();
    $('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
    $('body').removeClass('scrollDisabled').css('margin-top', 0);
    $(window).scrollTop(y_offsetWhenScrollDisabled);
}
8
Rajat Gupta

galambalazs postによると、タッチデバイスのサポートを追加して、タッチはできるが上下にスクロールはできないようにします。

function disable_scroll() {
   ...
   document.ontouchmove = function(e){ 
        e.preventDefault(); 
   }
}

function enable_scroll() {
   ...
   document.ontouchmove = function(e){ 
     return true; 
   }
}
7
jvalen

別の解決策:

body {
    overflow-y: scroll;
    width: 100%;
    margin: 0 auto;
}

このようにあなたは常に垂直スクロールバーを持っています、しかし私のコンテンツのほとんどはビューポートより長いので、これは私には問題ありません。コンテンツは別のdivで中央揃えされていますが、本文にマージンを設定しなくても、コンテンツは左側に残ります。

これらは私が私のポップアップ/モーダルを表示するために使用する2つの関数です:

var popup_bodyTop = 0;
var popup_bodyLeft = 0;

function popupShow(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');

    // remember current scroll-position
    // because when setting/unsetting position: fixed to body
    // the body would scroll to 0,0
    popup_bodyLeft = $(document).scrollLeft();
    popup_bodyTop  = $(document).scrollTop();

    // invert position
    var x = - popup_bodyLeft;
    var y = - popup_bodyTop;

    $('body').css('position', 'fixed');
    $('body').css('top', y.toString() +'px');
    $('body').css('left', x.toString() +'px');
}

function popupHide(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');
    $('body').css('position', '');
    $('html, body').scrollTop(popup_bodyTop);
    $('html, body').scrollLeft(popup_bodyLeft);
}

結果:背景がスクロールできず、スクロールバーが左にあるためにコンテンツの位置が変更されません。現在のFF、Chrome、およびIE 10でテスト済み。

4
Marco

Chrome 56および他の最近のブラウザの時点で、addEventListenername__を機能させるには、preventDefaultname__呼び出しにpassive:falseを追加する必要があります。それで、私はこれを使って携帯電話のスクロールを止めます。

function preventDefault(e){
    e.preventDefault();
}

function disableScroll(){
    document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll(){
    document.body.removeEventListener('touchmove', preventDefault, { passive: false });
}
3
Hokascha

これはどう? (jQueryを使っているのなら)

var $window = $(window);
var $body = $(window.document.body);

window.onscroll = function() {
    var overlay = $body.children(".ui-widget-overlay").first();

    // Check if the overlay is visible and restore the previous scroll state
    if (overlay.is(":visible")) {
        var scrollPos = $body.data("scroll-pos") || { x: 0, y: 0 };
        window.scrollTo(scrollPos.x, scrollPos.y);
    }
    else {
        // Just store the scroll state
        $body.data("scroll-pos", { x: $window.scrollLeft(), y: $window.scrollTop() });
    }
};
3
Dan

削除したスクロールで何を達成したいかに応じて、スクロールを削除したい要素を(クリックで、または一時的にスクロールを無効にしたいその他のトリガーで)修正できます。

私は "temp no scroll"ソリューションを探していましたが、私のニーズでは、これで解決しました

クラスを作る

.fixed{
    position: fixed;
}

それからJqueryと

var someTrigger = $('#trigger'); //a trigger button
var contentContainer = $('#content'); //element I want to temporarily remove scroll from

contentContainer.addClass('notfixed'); //make sure that the element has the "notfixed" class

//Something to trigger the fixed positioning. In this case we chose a button.
someTrigger.on('click', function(){

    if(contentContainer.hasClass('notfixed')){
        contentContainer.removeClass('notfixed').addClass('fixed');

    }else if(contentContainer.hasClass('fixed')){
        contentContainer.removeClass('fixed').addClass('notfixed');
    };
});

私は、これがすべてのブラウザでうまく機能し、また携帯機器(iPhone、タブレットなど)で簡単に使用できるようにするための十分に簡単な解決策であることを知りました。要素は一時的に固定されているので、スクロールはありません:)

注意! "contentContainer"要素の配置によっては、左から調整する必要があるかもしれません。固定クラスがアクティブなときに、その要素にcss left値を追加することで簡単に実行できます。

contentContainer.css({
    'left': $(window).width() - contentContainer.width()/2 //This would result in a value that is the windows entire width minus the element we want to "center" divided by two (since it's only pushed from one side)
});
3
axelra82

私はshowModalDialogを使って、二次ページをモーダルダイアログとして表示します。

メインウィンドウのスクロールバーを隠すには:

document.body.style.overflow = "hidden";

モーダルダイアログを閉じるときに、メインウィンドウのスクロールバーを表示します。

document.body.style.overflow = "scroll";

ダイアログからメインウィンドウの要素にアクセスするには:

parent.document.getElementById('dialog-close').click();

showModalDialog:(元のコードの29行目以降)を検索している人だけのために

document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.body.style.overflow = "hidden";//****
document.getElementById('dialog-close').addEventListener('click', function(e) {
    e.preventDefault();
    document.body.style.overflow = "scroll";//****
    dialog.close();
});
3
Zolfaghari

受け入れられた答えのようにイベントをキャンセルすることは私の意見では恐ろしい方法です:/

代わりに私は以下のposition: fixed; top: -scrollTop();を使いました。

デモ: https://jsfiddle.net/w9w9hthy/5/

私のjQueryのポップアッププロジェクトから: https://github.com/seahorsepip/jPopup

//Freeze page content scrolling
function freeze() {
    if($("html").css("position") != "fixed") {
        var top = $("html").scrollTop() ? $("html").scrollTop() : $("body").scrollTop();
        if(window.innerWidth > $("html").width()) {
            $("html").css("overflow-y", "scroll");
        }
        $("html").css({"width": "100%", "height": "100%", "position": "fixed", "top": -top});
    }
}

//Unfreeze page content scrolling
function unfreeze() {
    if($("html").css("position") == "fixed") {
        $("html").css("position", "static");
        $("html, body").scrollTop(-parseInt($("html").css("top")));
        $("html").css({"position": "", "width": "", "height": "", "top": "", "overflow-y": ""});
    }
}

このコードは、幅、高さ、スクロールバー、およびページジャンプの問題を考慮に入れています。

上記のコードで解決された可能性のある問題:

  • 幅、設定位置を固定する場合、html要素の幅は100%より小さくなります。
  • 高さ、上記と同じ
  • スクロールバー、位置設定を固定すると、水平方向のページジャンプが発生する前にスクロールバーがあっても、ページのコンテンツにスクロールバーが表示されなくなりました。
  • ページジャンプ、位置設定が固定されている場合、ページのscrollTopが無効になり、縦方向のページジャンプが発生する

誰かが上記のページのフリーズ/アンフリーズコードに何か改善があれば私に知らせてください。そうすれば私は私のプロジェクトにそれらの改善を加えることができます。

2
seahorsepip

これは古い質問ですが、非常に似たようなことをしなければならず、しばらくして答えを探してさまざまなアプローチを試みると、非常に簡単な解決策を使用することになりました。

私の問題は非常に似通っていて、ほとんど同じで、違いはスクロールバーを実際に表示する必要はないということです - 私はオーバーレイが表示されている間ページ幅が変わらないように。

オーバーレイを画面にスライドさせ始めると、次のようになります。

$('body').addClass('stop-scrolling').css('margin-right', 8);

オーバーレイを画面からスライドさせた後、次のようにします。

$('body').removeClass('stop-scrolling').css('margin-right', 0);

重要: absoluteのとき私のオーバーレイはvisibleright: 0pxに配置されるのでこれは完璧に動作します。

1
user2430829

シャイアンフォーブスの答え、そして私がここでfcalderanで見つけたものの上に構築する: それを隠さないでスクロールを無効にするだけ? そしてスクロールバーが消えるというHallodomの問題を修正する

CSS:

.preventscroll{
    position: fixed;
    overflow-y:scroll;
}

JS:

whatever.onclick = function(){
    $('body').addClass('preventscroll');
}
whatevertoclose.onclick = function(){
    $('body').removeClass('preventscroll');
}

このコードではページの先頭にジャンプしますが、fcalderanのコードには回避策があると思います。

1
Quibble

このコードはChrome 56以降で動作します(元の回答はChromeでは動作しません)。

DomUtils.enableScroll()を使用して、スクロールを有効にします。

DomUtils.disableScroll()を使用して、スクロールを無効にします。

class DomUtils {
  // left: 37, up: 38, right: 39, down: 40,
  // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
  static keys = { 37: 1, 38: 1, 39: 1, 40: 1 };

  static preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;
  }

  static preventDefaultForScrollKeys(e) {
    if (DomUtils.keys[e.keyCode]) {
      DomUtils.preventDefault(e);
      return false;
    }
  }

  static disableScroll() {
    document.addEventListener('wheel', DomUtils.preventDefault, {
      passive: false,
    }); // Disable scrolling in Chrome
    document.addEventListener('keydown', DomUtils.preventDefaultForScrollKeys, {
      passive: false,
    });
  }

  static enableScroll() {
    document.removeEventListener('wheel', DomUtils.preventDefault, {
      passive: false,
    }); // Enable scrolling in Chrome
    document.removeEventListener(
      'keydown',
      DomUtils.preventDefaultForScrollKeys,
      {
        passive: false,
      }
    ); // Enable scrolling in Chrome
  }
}
1
PerrierCitror

私は同じ問題を抱えています、以下は私がそれを扱う方法です。

/* file.js */
var body = document.getElementsByTagName('body')[0];
//if window dont scroll
body.classList.add("no-scroll");
//if window scroll
body.classList.remove("no-scroll");

/* file.css */
.no-scroll{
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

これが助けになることを願っています。

1
sou yang

いいえ、イベント処理は行いません。

  • すべてのイベントが身体に届くことが保証されているわけではありません。

  • テキストを選択して下に移動すると、実際には文書がスクロールされます。

  • イベントデタッチの段階でsthがうまくいかないのなら、あなたは運命にある。

隠したtextareaでコピー&ペーストをしてコピーするたびにページがスクロールするのではないかと私はこれを辛抱しました。なぜなら内部的にdocument.execCommand('copy')を呼び出す前にtextareaを選択する必要があるからです。

とにかく、それが私のやり方です、setTimeout()に注意してください。

document.body.setAttribute('style','overflow:hidden;');
// do your thing...
setTimeout(function(){document.body.setAttribute('style','overflow:visible;');}, 500);

スクロールバーが一瞬消えると勢いが点滅しますが、それは許容できることです。

1
centurian

最も簡単な方法は次のとおりです。

$("body").css("overflow", "hidden"); // Remove the scroll bar temporarily

元に戻すには:

$("body").css("overflow", "auto");

実装は簡単ですが、唯一の欠点は次のとおりです。

  • 中央揃え(水平方向)の場合、ページは少し左にジャンプします。

これはスクロールバーが削除され、ビューポートが少し広くなったためです。

1
Daan

これがスクロールを止めるための私の解決策です(jQueryはありません)。サイドメニューが表示されたときにスクロールを無効にするために使用します。

<button onClick="noscroll()" style="position:fixed; padding: 8px 16px;">Disable/Enable scroll</button>
<script>
var noscroll_var;
function noscroll(){
  if(noscroll_var){
    document.getElementsByTagName("html")[0].style.overflowY = "";
    document.body.style.paddingRight = "0";
    noscroll_var = false
  }else{
    document.getElementsByTagName("html")[0].setAttribute('style', 'overflow-y: hidden !important');
    document.body.style.paddingRight = "17px";
    noscroll_var = true
  }
}/*noscroll()*/
</script>

<!-- Just to fill the page -->
<script>
  for(var i=0; i <= 80; i++){
    document.write(i + "<hr>")
  }
</script>

スクロールバーの消えた分を補うために17pxの右詰めをしました。しかし、これもまた問題があります。主にモバイルブラウザの場合です。 this に従ってバーの幅を取得することで解決しました。

このペンの中で一緒に。

1
Josep81

Jqueryのanimateコマンドを使用してdivをアニメートしようとしたとき、私はモバイルスクリーンではなくラップトップでは同様のアニメーション問題を抱えていました。そこで私は、ウィンドウのスクロール位置を非常に頻繁に復元するタイマーを使うことにしました。この解決策は、Samsung Galaxy-2やiphone-5のような小さな画面のモバイル機器で完璧に機能しました。

このアプローチのメインロジック :ウィンドウのスクロール位置を元のスクロール位置に設定するタイマーは、jquery animateコマンドの前に開始し、アニメーションが完了したらこのタイマーをクリアする必要があります(original scroll positionはアニメーションの直前の位置です)開始します。

驚いたことに タイマーの間隔が1 millisecondであれば、アニメーションの期間中、ドキュメントは実際には静止しているように見えました。

//get window scroll position prior to animation
//so we can keep this position during animation
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;

//NOTE:restoreTimer needs to be global variable
//start the restore timer
restoreTimer = setInterval(function() {
    window.scrollTo(xPosition, yPosition);
}, 1);

//animate the element emt
emt.animate({
    left: "toggle",
    top: "toggle",
    width: "toggle",
    height: "toggle"
}, 500, function() {
    //when animation completes, we stop the timer
    clearInterval(restoreTimer);
});

うまくいった他の解決策 :この記事の下のMohammad Aniniによるスクロールを有効/無効にするための回答に基づいて、私は以下のような修正版のコードがうまくいったこともわかりました。

//get current scroll position
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;

//disable scrolling
window.onscroll = function() {
    window.scrollTo(xPosition, yPosition);
};

//animate and enable scrolling when animation is completed
emt.animate({
    left: "toggle",
    top: "toggle",
    width: "toggle",
    height: "toggle"
}, 500, function() {
    //enable scrolling when animation is done
    window.onscroll = function() {};
});
0
Sunil

私が組み立てたもの

jsfiddle

document.onwheel = function(e) {
  // get the target element
  target = e.target;
  // the target element might be the children of the scrollable element
  // e.g., "li"s inside an "ul", "p"s inside a "div" etc.
  // we need to get the parent element and check if it is scrollable
  // if the parent isn't scrollable, we move up to the next parent
  while (target.scrollHeight <= target.clientHeight) {
    // while looping parents, we'll eventually reach document.body
    // since body doesn't have a parent, we need to exit the while loop
    if (target == document.body) {
      break;
    }
    target = target.parentElement;
  }
  // we want this behaviour on elements other than the body
  if (target != document.body) {
    // if the scrollbar is at the top and yet if it still tries to scroll up
    // we prevent the scrolling
    if (target.scrollTop <= 0 && e.deltaY < 0) {
      e.preventDefault();
    }
    // similarly, if the scrollbar is at the bottom and it still tries to scroll down
    // we prevent it
    else if (target.clientHeight + target.scrollTop >= target.scrollHeight && e.deltaY > 0) {
      e.preventDefault();
    }
  }
};
body {
  background: gainsboro;
}

#box {
  width: 300px;
  height: 600px;
  padding: 5px;
  border: 1px solid silver;
  margin: 50px auto;
  background: white;
  overflow: auto;
}
<div id="box">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>
0
akinuri

私のために働いた簡単な解決策(一時的にウィンドウスクロールを無効にする)。

このフィドルに基づく: http://jsfiddle.net/dh834zgw/1/ /

次のスニペット(jqueryを使用)はウィンドウスクロールを無効にします。

 var curScrollTop = $(window).scrollTop();
 $('html').toggleClass('noscroll').css('top', '-' + curScrollTop + 'px');

そしてあなたのCSSでは:

html.noscroll{
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
    z-index: 10;
 }

モーダルを削除するときは、htmlタグのnoscrollクラスを削除することを忘れないでください。

$('html').toggleClass('noscroll');
0
ling
var winX = null, winY = null;
window.addEventListener('scroll', function () {
    if (winX !== null && winY !== null) {
        window.scrollTo(winX, winY);
    }
});
function disableWindowScroll() {
    winX = window.scrollX;
    winY = window.scrollY;
};
function enableWindowScroll() {
    winX = null;
    winY = null;
};
0
Văn Quyết

overflow = "hidden"でスクロールバーを非表示にするとページが少し踊るように見えるので、この問題についての私の見解には、ボディ幅に関する懸念も含まれています。次のコードは私には完璧に機能し、Angularアプローチに基づいています。

element.bind('mouseenter', function() {
    var w = document.body.offsetWidth;
    document.body.style.overflow = 'hidden';
    document.body.style.width = w + 'px';
});

element.bind('mouseleave', function() {
    document.body.style.overflow = 'initial';
    document.body.style.width = 'auto';
});
0
Fabio Nolasco

これは私がこれまでに得た最も簡単な解決策です。そして、私が他のすべてを試したことを信じて、これが最も簡単なものです。 Windowsデバイスの場合は 、システムのスクロールバー用のスペースを確保するためにページは右からプッシュされ、 IOS devices の場合はスペースを必要としません。ブラウザのスクロールバーそのため、これを使用することで、右側にパディングを追加する必要がなくなり、 本文またはHTMLのオーバーフローをcss で非表示にしたときにページがちらつくことはありません。

あなたがそれについて考えれば解決策は非常に簡単です。考えは、ポップアップが開かれた瞬間に window.scrollTop() に同じ正確な位置を与えることです。ウィンドウのサイズが変わったときにもその位置を変更します(スクロール位置が変わるとスクロール位置が変わります)。

だからここに行きます...

最初に、ポップアップが開いていることを知らせる変数を作成し、それを stopWindowScroll と呼びます。これを行わないと、ページ上の未定義変数のエラーが発生し、0に設定されます - アクティブではないためです。

$(document).ready(function(){
    stopWindowScroll = 0;
});

今すぐあなたがプラグインまたはカスタムとして使用しているポップアップをトリガーするあなたのコード内の任意の関数にオープンポップアップ関数の魔女をすることができます。この場合それはクリック機能の簡単な文書が付いている簡単なカスタムポップアップです。

$(document).on('click','.open-popup', function(){
    // Saving the scroll position once opening the popup.
    stopWindowScrollPosition = $(window).scrollTop();
    // Setting the stopWindowScroll to 1 to know the popup is open.
    stopWindowScroll = 1;
    // Displaying your popup.
    $('.your-popup').fadeIn(300);
});

それで私たちが次にやることはclose popup関数を作成することです、私は再びあなたが既に作成したかプラグインの中で使用しているどんな関数でもよいです。重要なことは、いつ開いているか閉じているかを知るために、 stopWindowScroll 変数を1または0に設定するために、これら2つの関数が必要なことです。

$(document).on('click','.open-popup', function(){
    // Setting the stopWindowScroll to 0 to know the popup is closed.
    stopWindowScroll = 0;
    // Hiding your popup
    $('.your-popup').fadeOut(300);
});

それからwindow.scroll関数を作成して、上記の stopWindowScroll が1に設定されたらスクロールを防止できるようにします。

$(window).scroll(function(){
    if(stopWindowScroll == 1) {
         // Giving the window scrollTop() function the position on which
         // the popup was opened, this way it will stay in its place.
         $(window).scrollTop(stopWindowScrollPosition);
    }
});

それでおしまい。ページに独自のスタイルを除いて、これを機能させるのに必要なCSSはありません。これは私にとって魅力的なように働きました、そしてそれがあなたと他の人々を助けることを願っています。

これがJSFiddleの実用的な例です。

JS Fiddle例

これが助けになったかどうか私に知らせてください。よろしく。

0
Architect

私は他の site でこの答えを見つけました:

スクロールを無効にする:

$( ".popup").live({
    popupbeforeposition: function(event, ui) {
    $("body").on("touchmove", false);
}
});

ポップアップを閉じた後、スクロールを放します。

$( ".popup" ).live({
    popupafterclose: function(event, ui) {
    $("body").unbind("touchmove");
}
});
0
pennstump

スクロール長をグローバル変数に格納し、必要に応じてそれを復元します。

var sctollTop_length = 0;

function scroll_pause(){
  sctollTop_length = $(window).scrollTop();
  $("body").css("overflow", "hidden");
}

function scroll_resume(){
  $("body").css("overflow", "auto");
  $(window).scrollTop(sctollTop_length);
}
0
Kareem

galambalazsの解決策は素晴らしいです! ChromeとFirefoxの両方で私にとっては完璧に機能しました。また、ブラウザウィンドウからデフォルトイベントが発生しないように拡張することもできます。あなたがキャンバス上でアプリをやっているとしましょう。あなたはこれをすることができます:

var events = {
  preventDefault: function(e) {
    e = e || window.event;
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;  
  },

  //spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36,
  //left: 37, up: 38, right: 39, down: 40
  keys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
  keydown: function(e) {
    for (var i = events.keys.length; i--;) {
      if (e.keyCode === events.keys[i]) {
        events.preventDefault(e);
        return;
      }
    }
  },

  wheel: function(e) {
    events.preventDefault(e);
  },

  disable: function() {
    if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', events.wheel, false);
    }
    window.onmousewheel = document.onmousewheel = events.wheel;
    document.onkeydown = helpers.events.keydown;
  },

  enable: function() {
    if (window.removeEventListener) {
      window.removeEventListener('DOMMouseScroll', events.wheel, false);
    }
    window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
  }
}

マウス、キーボード、タッチイベントなどの独自のイベントを処理するとしましょう。外出:

function setMouseEvents(canvas) {
  var useCapture = false;

  //Mouse enter event
  canvas.addEventListener('mouseenter', function(event) {
    events.disable();
  }, useCapture);

  //Mouse leave event
  canvas.addEventListener('mouseleave', function(event) {
    events.enable();
  }, useCapture);
}

このハックで右クリックメニューを無効にすることもできます。

function disableRightClickMenu(canvas) {
  var my_gradient = canvas.context.createLinearGradient(0, 0, 0, 225);
  my_gradient.addColorStop(0, "white");
  my_gradient.addColorStop(1, "white");
  canvas.context.fillStyle = my_gradient;
  canvas.context.fillRect(0, 0, canvas.width, canvas.height);
  canvas.oncontextmenu = function() { return false; };
}
0
Rafael

タッチデバイスについても同様の問題があります。要素に "touch-action:none"を追加することで問題は解決しました。

詳細については。これをチェックしてください: -

https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

0
Gurpreet

スペースバーのスクロールをブロックしてブラウザのスクロールバーを非表示にすることができます。

$(document).keydown(function(event) {
    if (event.keyCode == 32) {
        return false;

    }
});

document.documentElement.style.overflow = 'hidden';
document.body.scroll = 'no';
0
santyas