我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)

当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。


当前回答

为了防止跳楼,我用了这个

export function toggleBodyScroll(disable) {
  if (!window.tempScrollTop) {
    window.tempScrollTop = window.pageYOffset; 
    // save the current position in a global variable so I can access again later

  }
  if (disable) {
    document.body.classList.add('disable-scroll');
    document.body.style.top = `-${window.tempScrollTop}px`;
  } else {
    document.body.classList.remove('disable-scroll');
    document.body.style.top = `0px`;
    window.scrollTo({top: window.tempScrollTop});
    window.tempScrollTop = 0;
  }
}

在CSS中

.disable-scroll {
  height: 100%;
  overflow: hidden;
  width: 100%;
  position: fixed;
}

其他回答

CSS

  overflow-y: hidden
}

Javascript
``let body = document.querySelector('body');
if(condition)  {
 //disable scroll on the entire body
 body?.classList.add("disable-scroll");
} 
else {
 //to remove the class attrib
 body?.removeAttribute("class");
 //or to remove the disable-scroll class only
 body?.classList.remove("dissble-scroll");
}

这比长代码好多了。容易理解

这个怎么样?(如果你正在使用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() });
    }
};

网站我继承了,有一个滚动的链接。为了暂时禁用滚动单击特定按钮,这对我来说是有效的:

$(document).ready(function() {      
    $('button.class-name').click(function(event) {
        disableScroll();
        setTimeout(enableScroll, 500);  
    });
});


function disableScroll() {
    scrollTop =  window.pageYOffset || document.documentElement.scrollTop; 
    scrollLeft =  window.pageXOffset || document.documentElement.scrollLeft, 

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

function enableScroll() { 
    window.onscroll = function() {}; 
} 
var winX = null;
var 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;
}

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

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