我想让我的身体在使用鼠标滚轮时停止滚动,而我的网站上的Modal(来自http://twitter.github.com/bootstrap)是打开的。
当模式被打开时,我试图调用下面的javascript片段,但没有成功
$(window).scroll(function() { return false; });
AND
$(window).live('scroll', function() { return false; });
请注意,我们的网站放弃了对IE6的支持,IE7+需要兼容。
警告:下面的选项与Bootstrap v3.0无关。X,因为在这些版本中滚动被显式地限制在模态本身。如果禁用轮事件,可能会无意中阻止一些用户在高度大于视口高度的模态中查看内容。
还有另一个选择:车轮事件
滚动事件不可取消。但是,可以取消鼠标滚轮和滚轮事件。需要注意的是,并不是所有的传统浏览器都支持它们,Mozilla最近才在Gecko 17.0中添加了对后者的支持。我不知道它们的全部分布,但IE6+和Chrome确实支持它们。
下面是如何利用它们的方法:
$('#myModal')
.on('shown', function () {
$('body').on('wheel.modal mousewheel.modal', function () {
return false;
});
})
.on('hidden', function () {
$('body').off('wheel.modal mousewheel.modal');
});
JSFiddle
这是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();
}
};
最好的解决方案是大多数答案所使用的css-only body{overflow:hidden}解决方案。一些答案提供了一个修复,也防止“跳跃”造成的消失滚动条;然而,没有一个太优雅。我写了这两个函数,它们看起来工作得很好。
var $body = $(window.document.body);
function bodyFreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('overflow', 'hidden');
$body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}
function bodyUnfreezeScroll() {
var bodyWidth = $body.innerWidth();
$body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
$body.css('overflow', 'auto');
}
查看jsFiddle的使用情况。