如何使用箭头键禁用 FF 中的页面滚动
我正在构建一个包含主题和项目的菜单。每个主题都可以通过单击展开和折叠。我的任务是使用向上和向下箭头键在菜单主题和项目之间移动成为可能。我已经这样做了,但问题是,当页面大于窗口时,按箭头键时页面会滚动。我尝试过使用:
document.body.style.overflow = "hidden";
来停止页面滚动。因此,例如,当我单击“主题 2”时,我可以继续使用箭头键转到下一个主题/项目。之后,如果我单击屏幕上的其他任何位置,我会将溢出设置回自动,并且页面可以再次滚动。
这在 IE 中有效,但在 FF 中无效。在 FF 中,滚动条被删除,鼠标滚轮不会滚动页面,但箭头键仍然可以滚动。所以我的问题是如何解决这个问题 或者更好的是,当焦点位于任何菜单元素上时如何不滚动页面?因此我不会使用溢出属性。
I'm building a menu with topics and items. Each topic can be expanded and collapsed by clicking on it. My task is to make it possible to move through menu topics and items with the up and down arrow keys. I've done this already, but the problem is that when the page is bigger than the window, the page is scrolling when pressing the arrow keys. I've tried using:
document.body.style.overflow = "hidden";
to stop the page from scrolling. Thus when I click on 'Topic2' for example I can continue using the arrow keys to go to next topic/item. After that if I click anywhere else on the screen I set the overflow back to auto and the page can be scrolled again.
This works in IE, but not in FF. In FF the scrollbars are being removed and the mousewheel doesn't scroll the page, but the arrow keys still DO. So my question is how to fix that,
or better, how not to scroll the page when the focus is on any menu element? Thus I won't use the overflow property.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须将 keydown 事件绑定到文档,如果事件键码与任何箭头键(37 到 40)匹配,则返回 false。这样箭头按下就不会再继续了。
您可以轻松地扩展它,使其仅在菜单处于活动状态时才起作用,但是如果没有看到其中的一些代码,就不可能给您提供示例。
You have to bind a keydown event to the document, and if the event keycode matches any of the arrow keys (37 through 40), return false. That way the arrow press won't go any further.
You can easily expand on that to work only when your menu is active, but without seeing some of it's code, it's impossible to give you an example.
下面的代码已经解决了问题
below code has fixed the problem
我能看到的唯一方法是拦截
keydown
事件并自己进行模糊/聚焦。捕获这些按键似乎存在一些问题,请参阅这个问题< /a> 一些看起来很有前途的(基于 JQuery 的)示例。
The only way I can see is intercepting the
keydown
event and doing the blurring/focusing yourself.There seem to be some gotchas with catching those keys, see this question for a number of (JQuery based) examples that look quite promising.