我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
当前回答
我发现改变身体的风格是没有必要的。
我们唯一需要做的就是防止整个文档(html元素)出现y滚动。
我们可以用Javascript来创建和销毁样式表。我是这样做的:
https://jsfiddle.net/3os72ryk/
var scroll_style_element;
function disable_scrolling(){
// Create a style sheet we will only use to disable scrolling :
scroll_style_element = document.createElement('style');
document.head.appendChild(scroll_style_element);
const scroll_style_sheet = scroll_style_element.sheet;
scroll_style_sheet.insertRule('html{height:100%;overflow-y:hidden;}', scroll_style_sheet.cssRules.length);
}
function enable_scrolling(){
if( scroll_style_element ) document.head.removeChild(scroll_style_element);
}
非常有兴趣知道是否有人发现这种方法有问题,所以如果你发现了,请在下面评论。
其他回答
我在另一个网站上找到了答案:
禁用滚动:
$( ".popup").live({
popupbeforeposition: function(event, ui) {
$("body").on("touchmove", false);
}
});
关闭后弹出窗口释放滚动:
$( ".popup" ).live({
popupafterclose: function(event, ui) {
$("body").unbind("touchmove");
}
});
这个答案提出了一个解决方案,用于删除overflow: hidden时发生的“bump”。由于编辑被拒绝,下面是:
要删除overflow: hidden应用时发生的“凹凸”,您可以计算滚动条的宽度并用margin代替它。下面是body元素的例子:
const bodyScrollControls = {
scrollBarWidth: window.innerWidth - document.body.clientWidth,
disable() {
document.body.style.marginRight = `${this.scrollBarWidth}px`;
document.body.style.overflowY = 'hidden';
},
enable() {
document.body.style.marginRight = null;
document.body.style.overflowY = null;
},
};
如果元素已经有右边距,那么获取现有的右边距并为其添加滚动条宽度应该不是问题。
最简单的方法是:
$("body").css("overflow", "hidden"); // Remove the scroll bar temporarily
要撤消它:
$("body").css("overflow", "auto");
很容易实现,但唯一的缺点是:
如果页面是居中对齐的(水平),它会向左跳一点。
这是由于滚动条被移除,并且视口变得更宽。
我在这篇文章中找到了解决方案。在我的上下文中,我希望禁用垂直滚动,当我在一个
像这样=>
let scrollContainer = document.getElementById('scroll-container');
document.getElementById('scroll-container').addEventListener(
"wheel",
(event) => {
event.preventDefault();
scrollContainer.scrollLeft += event.deltaY;
},
{
// allow preventDefault()
passive: false
}
);
对我来说,这并没有带来任何内容跳跃。
禁用滚动:
this.htmlBody = $('body')
this.scrollPos = document.documentElement.scrollTop
this.htmlBody.css('top', -this.scrollPos + 'px').addClass('disable-scroll')
重新启用滚动:
this.htmlBody.removeClass('disable-scroll')
$(window).scrollTop(this.scrollPos)
而CSS:
body.disable-scroll {
position: fixed;
width: 100%;
}