如何暂时禁用滚动?

坚强是说给别人听的谎言 提交于 2020-02-27 04:48:43

我使用的是scrollTo jQuery插件,想知道是否可以通过Java临时禁用window元素上的滚动吗? 我要禁用滚动的原因是,当您在scrollTo设置动画时滚动时,它真的很难看;)

当然,我可以做一个$("body").css("overflow", "hidden"); 然后在动画停止时将其重新设置为自动,但是如果滚动条仍然可见但处于非活动状态会更好。


#1楼

只需在正文中添加一个类即可:

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

#2楼

这个怎么样? (如果您使用的是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楼

我在另一个网站上找到了这个答案:

禁用滚动:

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

关闭弹出窗口后,滚动:

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

#4楼

根据要使用移除的滚动条实现的功能,您可以修复要从中移除滚动条的元素(单击时,或要暂时停用滚动条的任何其他触发器)

我一直在寻找“临时无滚动”解决方案,而对于我的需求,这解决了它

上课

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

#5楼

根据galambalazs的帖子,我将添加对触摸设备的支持,使我们可以触摸但不能上下滚动:

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

function enable_scroll() {
   ...
   document.ontouchmove = function(e){ 
     return true; 
   }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!