javascript 使用箭头键滚动 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8805550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:38:21  来源:igfitidea点击:

Scroll div with arrow keys

javascripthtmlcss

提问by dcn

This is similar to SO: how to move a div with arrow keys, so maybe a clear and informed 'no' suffices as an answer:

这类似于SO: how to move a div with arrow keys,所以也许一个明确而明智的“不”就足以作为答案:

Can I make an overflowing div a "default scroll target" that reacts to arrow-up/down/page-down/space the same way as an overflowing document(i.e. scrolls down the content)? The page itself does not have a scrollbar (simple example below). In particular, can this be accomplished without explicitly tracking key events(neither directly nor hidded by a JS library)?

我可以将溢出的 div 设为“默认滚动目标”,它对向上/向下/向下/向下/向下箭头/空格的反应方式与溢出文档相同(即向下滚动内容)?页面本身没有滚动条(下面的简单示例)。特别是,这是否可以在不显式跟踪关键事件(既不直接也不由 JS 库隐藏)的情况下完成?

<html>
 <body>
  <div id="contentcontainer" style="height:200px;width:200px;overflow:scroll">
   <div id="innercontent" style="height:2000px;">foo</div>
  </div>
 </body>
</html>

Edit:Of course the above works after I click into the div. Basically, I want to avoid having to do that...

编辑:当然,在我点击进入 div 后,上述内容有效。基本上,我想避免这样做......

回答by dhasenan

In order for an html element to be focusable, it must be reachable with the Tab key. This means you can call .focus()on a link or an input. Additionally, bodyelements are always focusable.

为了使 html 元素可聚焦,它必须可通过 Tab 键访问。这意味着您可以调用.focus()链接或输入。此外,body元素始终是可聚焦的。

You need to make your div reachable with the Tab key. You can accomplish this by setting the tabindexproperty on it. If you do not actually want people to be able to tab into that div, you can set the tabindex to -1, which will prevent people from actually tabbing to it but will otherwise set the element up for tabbing and focus.

您需要使用 Tab 键使您的 div 可访问。您可以通过tabindex在其上设置属性来完成此操作。如果您实际上不希望人们能够在该 div 中使用 Tab,则可以将 tabindex 设置为 -1,这将阻止人们实际使用 Tab 键,但否则会将元素设置为 Tab 键和焦点。

Source: http://help.dottoro.com/ljpkdpxb.php

来源:http: //help.dottoro.com/ljpkdpxb.php

回答by Luc Laverdure

Browsers usually have this behavior built-in,

浏览器通常内置了这种行为,

In order to use arrow keys to scroll down your div, you must have an element within focused.

为了使用箭头键向下滚动您的 div,您必须在焦点内有一个元素。

Lookup http://api.jquery.com/focus/

查找http://api.jquery.com/focus/