我需要使一个网页滚动只能通过滚动条。我试图找到如何捕捉滚动条事件,但我认为这是不可能的。目前我使用的是以下函数:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
function wheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
}但在我的情况下,它们不是很有用,因为它们会阻止所有的滚动事件。你有什么想法吗?我已经考虑了3天了,我没有找到任何答案(还有问题)。谢谢!
发布于 2014-05-12 17:59:51
若要防止使用鼠标滚轮滚动窗口,请执行以下操作。
// Old Method
window.onwheel = function(){ return false; }EDIT (2020年1月):由@MatthewMorrone上面的代码通知窗口上绑定滚轮事件的,
window.document&window.document.body(标记为“旧方法”)不再工作。欲了解更多详情,请访问:https://www.chromestatus.com/features/6662647093133312
由于文档级滚轮/鼠标轮事件侦听器是treated as Passive,我们需要将此事件侦听器标记为活动。请检查以下代码以获得解决方案。更多信息:https://developers.google.com/web/updates/2019/02/scrolling-intervention
// New Working Method
window.addEventListener("wheel", e => e.preventDefault(), { passive:false })如果<div>或其他元素的内容是可滚动的,您可以这样阻止它:
document.getElementById('{element-id}').onwheel = function(){ return false; }干杯..。
发布于 2016-03-23 23:56:42
防止使用鼠标滚轮滚动窗口的jQuery解决方案:
$(window).bind('mousewheel DOMMouseScroll', function(event){ return false});如果您想要防止在单个DOM元素中使用鼠标滚轮滚动,请尝试以下操作:
$('#{element-id}').bind('mousewheel DOMMouseScroll', function (e) { return false; });在Firefox中使用了DOMMouseScroll事件,因此您必须同时侦听这两个事件。
发布于 2019-01-15 23:51:04
我目前正在使用它,它工作得很好。使用滚动条可以很好地工作,但鼠标滚轮不能工作。
我这样做的原因是,我有自定义代码来滚动我想要的方式,但如果不添加任何代码,它就不会在滚轮上滚动。
window.addEventListener('wheel', function(e) {
e.preventDefault();
// add custom scroll code if you want
}https://stackoverflow.com/questions/20026502
复制相似问题