在 IOS 和 Android 中防止拖动时页面滚动
我正在开发一个 html5 画布游戏,但我不知道如何处理触摸事件。当用户触摸屏幕并拖动时,浏览器将滚动页面。我想阻止它,并获取触摸开始和触摸结束位置。是否可以?
提前致谢
I'm working on a html5 canvas game, but I don't know how to handle touch events. When a user touch the screen, and drag, then the browser will scroll the page. I would like to prevent it, and get the touch start, and touch end position. Is it possible?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要覆盖默认的触摸行为以停止触摸事件拖动页面。显然,如果您的页面变得大于可用区域,您将需要再次处理它们,但当您制作游戏时,将假设您正在执行 100%/100% 布局。
编辑:这是关于触摸事件的 W3C 建议,这可能对您有用。
You need to override the default touch behaviour to stop touchevents dragging the page. Clearly, you'll need to handle them again if your page becomes larger than the available area, but as you're making a game, going to assume you're doing 100%/100% layout.
Edit: here's the W3C recommendation talking about touch events, which might be handy for you.
由于最新版本的 Chrome 进行了重大更改,上述答案不再正确。将触摸事件侦听器附加到文档或正文元素将导致事件侦听器以“被动”模式注册,从而导致对
preventDefault
的调用被忽略。有两种解决方案:
首选解决方案是使用 CSS 样式
touch-action
指定不应发生滚动(例如,值为“none”)在不合适的情况下(例如,如果交互类型应以在手势开始之前无法确定的方式动态更改),则事件侦听器必须注册时将第三个参数设置为
{ Passive: false }
(不过,您应该执行浏览器检测以确保首先支持此样式)。Due to breaking changes made in recent versions of Chrome, the above answers are no longer correct. Attaching a touch event listener to the document or body elements will cause the event listener to be registered in "passive" mode, which causes calls to
preventDefault
to be ignored.There are two solutions:
The preferred solution is to use the CSS style
touch-action
to specify that no scrolling should happen (e.g. with the value "none")In cases where this is not appropriate (e.g. if the type of interaction should change dynamically in a way that cannot be determined before the gesture begins) then the event listener must be registered with the third parameter set to
{ passive: false }
(you should perform browser detection to ensure that this style is supported first, though).如果您不想使用 jQuery mobile 或任何其他库,那么您可以尝试这个。
If you don't want to use jQuery mobile or any other library then you can try this.
这是一篇关于手机上的触摸和手势的好文章:
http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
Here's a good article about touching and gesturing on mobile phones:
http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
以下解决方案在拖动时防止滚动并且同时正常滚动工作(不拖动时)
不要忘记将
onDragstartHandler
和onDragendHandler
绑定到相关元素Following solution preventing scroll when dragging AND at the same time usual scroll is working (when not dragging)
Don't forget to bind
onDragstartHandler
andonDragendHandler
to related elements