How to disable scrolling temporarily?

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

    Depending on what you want to achieve with the removed scroll you could just fix the element that you want to remove scroll from (on click, or whatever other trigger you'd like to temporarily deactivate scroll)

    I was searching around for a "temp no scroll" solution and for my needs, this solved it

    make a class

    .fixed{
        position: fixed;
    }
    

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

    I found that this was a simple enough solution that works well on all browsers, and also makes for simple use on portable devices (i.e. iPhones, tablets etc). Since the element is temporarily fixed, there is no scroll :)

    NOTE! Depending on the placement of your "contentContainer" element you might need to adjust it from the left. Which can easily be done by adding a css left value to that element when the fixed class is active

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

提交回复
热议问题