Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Set keyboard focus to a <div>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...