복붙노트

[JQUERY] 어떻게 일시적으로 스크롤 해제하는 방법?

JQUERY

어떻게 일시적으로 스크롤 해제하는 방법?

해결법


  1. 1.스크롤 이벤트는 취소 할 수 없습니다. 그러나 이러한 상호 작용 이벤트를 취소하여 작업을 수행 할 수 있습니다 : 마우스 및 터치 스크롤 및 버튼은 스크롤과 관련.

    스크롤 이벤트는 취소 할 수 없습니다. 그러나 이러한 상호 작용 이벤트를 취소하여 작업을 수행 할 수 있습니다 : 마우스 및 터치 스크롤 및 버튼은 스크롤과 관련.

    // 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.preventDefault();
    }
    
    function preventDefaultForScrollKeys(e) {
      if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
      }
    }
    
    // modern Chrome requires { passive: false } when adding event
    var supportsPassive = false;
    try {
      window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
        get: function () { supportsPassive = true; } 
      }));
    } catch(e) {}
    
    var wheelOpt = supportsPassive ? { passive: false } : false;
    var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';
    
    // call this to Disable
    function disableScroll() {
      window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
      window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
      window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
      window.addEventListener('keydown', preventDefaultForScrollKeys, false);
    }
    
    // call this to Enable
    function enableScroll() {
      window.removeEventListener('DOMMouseScroll', preventDefault, false);
      window.removeEventListener(wheelEvent, preventDefault, wheelOpt); 
      window.removeEventListener('touchmove', preventDefault, wheelOpt);
      window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
    }
    

    UPDATE : 고정 크롬 데스크탑 및 수동 청취자 현대 모바일 브라우저


  2. 2.단순히 몸에 클래스를 추가하여 수행

    단순히 몸에 클래스를 추가하여 수행

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

    당신이 IE, FF, 사파리와 크롬에서 테스트, 스크롤을 다시 활성화 할 때 제거 다음 클래스를 추가합니다.

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

    모바일 기기의 경우,하는 TouchMove 이벤트를 처리해야합니다 :

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

    그리고에 바인딩 해제 스크롤을 다시 활성화하십시오. iOS6의 안드로이드 2.3.3에서 테스트

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

  3. 3.여기에 그것을 할 수있는 정말 기본적인 방법이있다 :

    여기에 그것을 할 수있는 정말 기본적인 방법이있다 :

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

    그것은 6으로 불안해의 종류입니다.


  4. 4.다음 솔루션은 기본적이지만 순수 자바 스크립트 (NO jQuery를)입니다 :

    다음 솔루션은 기본적이지만 순수 자바 스크립트 (NO jQuery를)입니다 :

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

  5. 5.스크롤하는 동안 현재 스크롤 위치를 유지하는 것이 솔루션은 일부 달리 가기 사용자가 다시 점프, 사용할 수 없습니다.

    스크롤하는 동안 현재 스크롤 위치를 유지하는 것이 솔루션은 일부 달리 가기 사용자가 다시 점프, 사용할 수 없습니다.

    그것은 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);
    

  6. 6.나는 이전 게시물에 답변을 미안하지만 나는 해결책을 찾고이 질문에 건너 온되었다.

    나는 이전 게시물에 답변을 미안하지만 나는 해결책을 찾고이 질문에 건너 온되었다.

    스크롤 스타일 :이 문제가 계속 용기를 100 % 높이와 오버 플로우-Y를주는 것처럼, 스크롤바를 표시하는 여러 해결 방법이 있습니다.

    몸에 숨겨진 : 제 경우에는 그냥 오버 플로우 추가하는 동안 표시 스크롤로 사업부를 만들었습니다 :

    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;
    

    이 쇼 회색 스크롤, 그것은 미래의 방문자에게 도움이되기를 바랍니다.


  7. 7.나는이 문제에 대한 해결책을 찾고했지만 (이 답변을 작성하는 현재) 위의 해결 방법의 어떤 만족하지 않은, 그래서 나는이 솔루션을 함께했다 ..

    나는이 문제에 대한 해결책을 찾고했지만 (이 답변을 작성하는 현재) 위의 해결 방법의 어떤 만족하지 않은, 그래서 나는이 솔루션을 함께했다 ..

    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. 8.galambalazs에 따르면 나는 우리가 접촉 할 수 있도록 터치 장치에 대한 지원을 추가하지만 것 게시 위 또는 아래로 더 스크롤 :

    galambalazs에 따르면 나는 우리가 접촉 할 수 있도록 터치 장치에 대한 지원을 추가하지만 것 게시 위 또는 아래로 더 스크롤 :

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

  9. 9.로 preventDefault 작업을 만들기 위해에서 addEventListener 호출에 거짓 : 크롬 56과 다른 현대적인 브라우저, 당신은 수동을 추가해야합니다. 내가 이것을 사용 그래서 모바일 스크롤 중지 :

    로 preventDefault 작업을 만들기 위해에서 addEventListener 호출에 거짓 : 크롬 56과 다른 현대적인 브라우저, 당신은 수동을 추가해야합니다. 내가 이것을 사용 그래서 모바일 스크롤 중지 :

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

  10. 10.아니, 이벤트 처리 때문에 함께 갈 것입니다 :

    아니, 이벤트 처리 때문에 함께 갈 것입니다 :

    나는 숨겨진 텍스트 영역으로 복사 - 붙여 넣기 작업을함으로써이 물린 내부적 내가 ( '사본') document.execCommand를 호출하기 전에 텍스트 영역을 선택해야하기 때문에 내가 복사본을 만들 때마다 어떤 페이지 스크롤을 생각했습니다.

    어쨌든 그게 내가가는 방법)합니다 (의 setTimeout을 발견,이다 :

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

    스크롤이 순간적으로 사라 같이 운동량 깜박이는 존재하지만 허용 나는 것입니다.


  11. 11.당신은 당신이 당신이에서 스크롤을 제거 할 것인지 요소를 고칠 수 제거 된 스크롤 달성하려는 작업에 따라 (클릭, 또는 어떤 다른 트리거에 일시적으로 비활성화 스크롤하고 싶습니다)

    당신은 당신이 당신이에서 스크롤을 제거 할 것인지 요소를 고칠 수 제거 된 스크롤 달성하려는 작업에 따라 (클릭, 또는 어떤 다른 트리거에 일시적으로 비활성화 스크롤하고 싶습니다)

    나는 "임시없이 스크롤"에 대한 솔루션 내 요구에 주위를 검색하고,이 그것을 해결

    클래스를 만들

    .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');
        };
    });
    

    나는이 모든 브라우저에서 잘 작동하고, 또한 휴대용 장치 (즉, 아이폰, 태블릿 등)에 간단한 사용하게 간단한 충분한 해결책 것을 발견했다. 요소가 일시적으로 고정되어 있기 때문에, 더 스크롤이 없습니다 :)

    노트! 당신의 "contentContainer"요소의 위치에 따라 왼쪽에서이를 조정해야 할 수도 있습니다. 어떤 쉽게 고정 클래스가 활성화 될 때 요소에 남아 CSS 값을 가산함으로써 수행 될 수있다

    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)
    });
    

  12. 12.또 다른 방법 :

    또 다른 방법 :

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

    이 방법 당신은 항상 수직 스크롤을 가지고 있지만 내 콘텐츠의 대부분은 더 이상 뷰포트보다,이 나에게 괜찮습니다. 내용은 별도의 사업부로 중앙에 있지만 몸에 다시 마진을 설정하지 않고 내 콘텐츠는 왼쪽에있을 것입니다.

    다음은 내 팝업 / 모달 표시하기 위해 사용하는 두 가지 기능이 있습니다 :

    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, 크롬과 IE 10 테스트.


  13. 13.

    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;
    };
    

  14. 14.이건 어때요? (당신이 jQuery를 사용하는 경우)

    이건 어때요? (당신이 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() });
        }
    };
    

  15. 15.나는 모달 대화로 보조 페이지를 보여주는,하여 showModalDialog를 사용하고 있습니다.

    나는 모달 대화로 보조 페이지를 보여주는,하여 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();
    });
    

  16. 16.내 의견에 끔찍한 방법으로 허용 대답에서와 같이 이벤트를 취소하면 다음과 같습니다 /

    내 의견에 끔찍한 방법으로 허용 대답에서와 같이 이벤트를 취소하면 다음과 같습니다 /

    대신에 나는 위치 사용 : 고정을; 맨 : -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": ""});
        }
    }
    

    이 코드는 고려, 폭, 높이, 스크롤 및 pagejump 문제를합니다.

    위의 코드로 해결 가능한 문제 :

    사람이 위의 페이지 동결에 대한 개선 사항이있는 경우 / 고정 취소 코드는 내 프로젝트에 그 개선을 추가 할 수 있도록 알려주세요.


  17. 17.나는 아래 내가 그것을 처리하는 방법입니다, 같은 문제가 있습니다.

    나는 아래 내가 그것을 처리하는 방법입니다, 같은 문제가 있습니다.

    /* 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;
    }
    

    이 도움을 바랍니다.


  18. 18.여기에 스크롤 (어떤 jQuery를) 막을 내 솔루션입니다. 나는 사이드 메뉴가 나타날 때 스크롤을 해제하는 데 사용합니다.

    여기에 스크롤 (어떤 jQuery를) 막을 내 솔루션입니다. 나는 사이드 메뉴가 나타날 때 스크롤을 해제하는 데 사용합니다.

    <버튼의 onclick = "noscroll ()"스타일 = "총수 : 고정; 패딩 : 8px 16px;"> / 비활성화 스크롤 사용