我正在寻找两个解决方案:如何禁用不需要垂直滚动的页面?以及如何禁用弹性反弹效果?
这个答案已经过时了,除非你正在为一个非常老的iOS设备开发...请查看其他解决方案
2011年的回答:对于在iOS Safari中运行的Web/HTML应用程序,您需要类似以下的东西
document.ontouchmove = function(event){
event.preventDefault();
}
针对iOS 5,您可能需要考虑以下内容:document.ontouchmove和iOS 5上的滚动
2014年9月更新:
您可以在此处找到更全面的方法:https://github.com/luster-io/prevent-overscroll。对于其中的许多有用的 Web 应用程序建议,请参见 http://www.luster.io/blog/9-29-14-mobile-web-checklist.html
2016年3月更新:上面的链接已经失效 - 可以查看 https://web.archive.org/web/20151103001838/http://www.luster.io/blog/9-29-14-mobile-web-checklist.html来获取归档版本。感谢@falsarella指出这一点。
onTouchMove: function(e) { e.stopPropagation(); e.stopImmediatePropagation(); }
。它会阻止事件传播到body上,但是body仍然不会反弹。编辑:这是在假定您设置了 $ ('div').on('touchmove', ...onTouchMove);
的情况下。 - Matt Kenefick你也可以将 body/html 的位置更改为 fixed:
body,
html {
position: fixed;
}
为了防止在现代移动浏览器中滚动,您需要添加passive: false。在找到这个解决方案之前,我一直在苦苦寻找使其正常工作的方法。我只在互联网上的一个地方发现过这个提及。
function preventDefault(e){
e.preventDefault();
}
function disableScroll(){
document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll(){
document.body.removeEventListener('touchmove', preventDefault);
}
{ passive: false }
它肯定不起作用!!!欢迎来到 StackOverflow 啊,伙计。 - SerCSS overscroll-behavior
在 iOS 16 中已得到支持。如果您的目标设备是 > iOS 16,则需将以下 CSS 添加到 html 根元素中以防止弹性反弹效果。
html {
overscroll-behavior: none;
}
html body {
overflow: hidden;
}
overflow: scroll;
-webkit-overflow-scrolling: touch;
<body>
上使用overflow:hidden
,这仍然是最好的解决方案。但是当打开键盘或滑动屏幕底部时,它将不再起作用。 - Fabian von Ellerts$(document).bind(
'touchmove',
function(e) {
e.preventDefault();
}
);
如何在iPad Safari中禁用滚动和弹跳效果:
document.addEventListener("touchmove", function (e) {
e.preventDefault();
}, { passive: false });
如果文档中有画布标签,有时它会影响画布内对象的可用性(例如:对象的移动);因此,请添加以下代码以进行修复。
document.getElementById("canvasId").addEventListener("touchmove", function (e) {
e.stopPropagation();
}, { passive: false });
var divInterval = setInterval(updateDivs,50);
function updateDivs(){
$("#swiffycontainer > div").bind(
'touchmove',
function(e) {
e.preventDefault();
}
);}
对于我来说,上述解决方案都不适用。这是我的解决方法。
html,body {
position: fixed;
overflow: hidden;
}
.the_element_that_you_want_to_have_scrolling{
-webkit-overflow-scrolling: touch;
}
在 iPhone 上测试过。只需将此 CSS 应用于目标元素容器,即可更改滚动行为,当手指离开屏幕时停止滚动。
-webkit-overflow-scrolling: auto
https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-overflow-scrolling