我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
这是TypeScript中的一种解决方案,可以轻松地阻止事件扩展,也可以处理移动设备。当禁用垂直滚动条时,这也不会导致水平跳转。
只需使用底部的导出函数,例如任何HTML元素上的onclick处理程序。如果不是在NodeJS环境中运行,只需删除该进程。客户端检查。
/**
* Handles scroll events for modal content
*/
const events = [
'DOMMouseScroll',
'mousewheel',
'wheel',
'touchmove',
'keydown',
'mousedown',
'scroll',
];
const preventDefault = (e: Event) => {
e.preventDefault();
e.stopPropagation();
return false;
};
let currentY: number;
const disableScroll = () => {
currentY = window.scrollY;
events.forEach((event) => {
window.addEventListener(event, preventDefault, {
passive: false,
});
});
const bodyStyle = document.body.style;
bodyStyle.setProperty('touch-action', 'none');
bodyStyle.setProperty('position', 'fixed');
bodyStyle.setProperty('overflow-y', 'scroll');
bodyStyle.setProperty('width', '100%');
bodyStyle.setProperty('top', `-${currentY}px`);
};
const enableScroll = () => {
events.forEach((event) => {
window.removeEventListener(event, preventDefault);
});
const bodyStyle = document.body.style;
bodyStyle.removeProperty('touch-action');
bodyStyle.removeProperty('position');
bodyStyle.removeProperty('overflow-y');
bodyStyle.removeProperty('width');
bodyStyle.removeProperty('top');
window.scroll(0, currentY);
};
/**
* Makes a component (e.g. popup) modal
*/
export const makeModal = () => {
if (process.client) {
disableScroll();
}
};
/**
* Makes a component (e.g. popup) non-modal
*/
export const makeNonModal = () => {
if (process.client) {
enableScroll();
}
};
我有一个边栏,是由复选框黑客生成的。
但主要思想是保存文档scrollTop,而不是在滚动窗口期间更改它。
我只是不喜欢页面跳转时,身体变成'溢出:隐藏'。
window.addEventListener('load', function() {
let prevScrollTop = 0;
let isSidebarVisible = false;
document.getElementById('f-overlay-chkbx').addEventListener('change', (event) => {
prevScrollTop = window.pageYOffset || document.documentElement.scrollTop;
isSidebarVisible = event.target.checked;
window.addEventListener('scroll', (event) => {
if (isSidebarVisible) {
window.scrollTo(0, prevScrollTop);
}
});
})
});
最著名的答案很简单,即。
body{
height: 100%;
overflow-y: hidden;
}
但是,如果你想在子/孙子中打开一个模态并停止滚动,该如何解决呢?更长期的解决方案是使用props或存储在Angular/React中,并改变body标签的高度和溢出属性。
另一种解决方案是从子/孙子组件获取主体,并相应地改变其高度和溢出以停止滚动。
在我的例子中,我只是这样做的
if(isModalExpanded){
document.body.style.overflow = "hidden";
document.body.style.height = "100%";
}
else{
document.body.style.overflow = "auto";
document.body.style.height = "auto";
}