将键盘焦点设置为< div> [英] Set keyboard focus to a <div>
问题描述
我有以下代码片段:
< div id =listbox1divstyle =z-index:95 ; background:white; overflow-y:auto; overflow-x:hidden; width:240; height:314px;>
< a id =focusLink2>< / a>
< table id =ptObj_listbox1 ...
我有一个建筑页< div>
元素动态显示(例如上面)。< div>
屏幕上。当页面生成div时,我想设置焦点。我不能在body标签上放置onLoad函数,因为我不知道何时会生成div。
< div>
标签不能直接在其上设置焦点,因此我将一个空的< a>
标记,其中包含我在以下函数中调用的标识:
函数setTableFocus(count){
var flinkText ='focusLink'+ count;
document.getElementById(flinkText).focus();
}
我没有收到任何错误,并且我知道当页面呈现时(通过警报)函数被调用。但是,当我使用箭头键或输入按钮时,整个页面移动(甚至没有分割帽子正在呈现数据)。
当我点击其中一个表格元素时(使用鼠标)。之后,keydown事件开始工作。我想要做的是将数据呈现给用户,并自动进行键盘驱动。
有没有人有任何建议我可以做到这一点?
如果您添加 div
> tabindex 属性。
请参阅: http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
tabindex值可以允许一些有趣的行为。
- 如果给定的值为-1,则该元素不能被标记为,但焦点可以是
以编程方式赋予元素(使用element.focus())。
- 如果给定的值为0,则可以通过键盘对该元素进行聚焦,
落入文档的标签流中。
- 大于0的值会创建一个优先级别级别,其中1是最重要的级别。
更新:在 http:// jsfiddle添加了一个简单演示.net / roberkules / sXj9m /
I have the following code snippet:
<div id="listbox1div" style="z-index:95; background:white; overflow-y:auto; overflow-x:hidden; width:240; height:314px;">
<a id="focusLink2"></a>
<table id="ptObj_listbox1...
I have a page that is building <div>
elements dynamically (such as above). This <div>
displays data on top of the main screen. When the page generates the divs I would like to set focus. I can not put an onLoad function on the body tag as I don't know when the divs will be generated.
A <div>
tag can not have focus set on it directly. So I put an empty <a>
tag with an id that I'm calling in the following function:
function setTableFocus(count){
var flinkText = 'focusLink'+count;
document.getElementById(flinkText).focus();
}
I'm not getting any errors and I know the function is being called when the page is presented (via alerts). However, when I using the arrow keys or enter button the entire page moves (not even the div that is presenting the data).
When I click on to one of the table elements (using the mouse). After that the keydown event starts working. What I would like this to do is to present the data to the user and automatically be keyboard driven.
Does anyone have any suggestions how I can accomplish this?
you can make a div
focusable if you add a tabindex
attribute.
see: http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
The tabindex value can allow for some interesting behaviour.
- If given a value of "-1", the element can't be tabbed to but focus can be given to the element programmatically (using element.focus()).
- If given a value of 0, the element can be focused via the keyboard and falls into the tabbing flow of the document.
- Values greater than 0 create a priority level with 1 being the most important.
UPDATE: added a simple demo at http://jsfiddle.net/roberkules/sXj9m/
这篇关于将键盘焦点设置为< div>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!