How to disable scrolling temporarily?

前端 未结 30 3319
萌比男神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:36

    I had a similar animation problem on mobile screens but not on laptops, when trying to animate a div using jquery's animate command. So I decided to use a timer that restored the window's scroll position so frequently that to a naked eye the document would appear static. This solution worked perfectly on a small screen mobile device like Samsung Galaxy-2 or iphone-5.

    Main Logic of this approach: The timer to set window's scroll position to original scroll position should be started before the jquery animate command, and then when animation is completed we need to clear this timer (original scroll position is the position just before animation starts).

    I found to my pleasant surprise that the document actually appeared static during the animation duration if the timer interval was 1 millisecond, which is what I was aiming for.

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

    ANOTHER SOLUTION that worked: Based on the answer by Mohammad Anini under this post to enable/disable scrolling, I also found that a modified version of code as below worked.

    //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() {};
    });
    

提交回复
热议问题