How to disable scrolling temporarily?

前端 未结 30 2475
萌比男神i
萌比男神i 2020-11-21 05:16

I\'m using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason

30条回答
  •  攒了一身酷
    2020-11-21 05:41

    Cancelling the event's as in the accepted answer is a horrible method in my opinion :/

    Instead I used position: fixed; top: -scrollTop(); below.

    Demo: https://jsfiddle.net/w9w9hthy/5/

    From my jQuery popup project: 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": ""});
        }
    }
    

    This code takes, width, height, scrollbar and pagejump issues into consideration.

    Possible issues resolved with above code:

    • width, when setting position fixed the html element width can be smaller then 100%
    • height, same as above
    • scrollbar, when setting position fixed the page content no longer has a scrollbar even when it had a scrollbar before resulting in a horizontal pagejump
    • pagejump, when setting position fixed the page scrollTop is no longer effective resulting in a vertical pagejump

    If anyone has any improvements to above page freeze/unfreeze code let me know so I can add those improvements to my project.

提交回复
热议问题