我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
当前回答
不,我不会使用事件处理,因为:
不是所有的事件都能保证到达身体, 选择文本并向下移动实际上是在滚动文档, 如果在分离某事物的阶段出了差错,你就完蛋了。
我已经咬了这个通过制作一个隐藏的文本区域复制粘贴动作,猜什么,页面滚动每当我做复制,因为内部我必须在我调用document.execCommand('copy')之前选择文本区域。
不管怎样,这就是我的方式,注意setTimeout():
document.body.setAttribute('style','overflow:hidden;');
// do your thing...
setTimeout(function(){document.body.setAttribute('style','overflow:visible;');}, 500);
当滚动条暂时消失时,会出现动量闪烁,但这是可以接受的。
其他回答
我在另一个网站上找到了答案:
禁用滚动:
$( ".popup").live({
popupbeforeposition: function(event, ui) {
$("body").on("touchmove", false);
}
});
关闭后弹出窗口释放滚动:
$( ".popup" ).live({
popupafterclose: function(event, ui) {
$("body").unbind("touchmove");
}
});
只需在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')
我发现改变身体的风格是没有必要的。
我们唯一需要做的就是防止整个文档(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);
}
非常有兴趣知道是否有人发现这种方法有问题,所以如果你发现了,请在下面评论。
不,我不会使用事件处理,因为:
不是所有的事件都能保证到达身体, 选择文本并向下移动实际上是在滚动文档, 如果在分离某事物的阶段出了差错,你就完蛋了。
我已经咬了这个通过制作一个隐藏的文本区域复制粘贴动作,猜什么,页面滚动每当我做复制,因为内部我必须在我调用document.execCommand('copy')之前选择文本区域。
不管怎样,这就是我的方式,注意setTimeout():
document.body.setAttribute('style','overflow:hidden;');
// do your thing...
setTimeout(function(){document.body.setAttribute('style','overflow:visible;');}, 500);
当滚动条暂时消失时,会出现动量闪烁,但这是可以接受的。
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");
}
这比长代码好多了。容易理解