开发者

Why doesn't focus() select my container div?

I have an index.html which has JavaScript:

byId("p").value = page;
byId("nav_container").focus();
document.forms["nav_form_main"].submit();

The focus part doesn't work here.

I want the browser to focus on a specific开发者_运维技巧 part of the page (almost at top).

I have tried putting the focus after the submit(), same issue there.


make sure the element you want to focus has an attribute tabindex="-1", otherwise that element is not focusable.

For example

<div id="myfocusablediv" tabindex="-1"></div>

When you set the tabindex=-1 for an element it allows it to get focus() through javascript. If instead you want it to get focus through tabbing through elements, then you would set the tabindex attribute to 0.


Here's what I do when I want to force a certain form element to have focus:

function setFocusFixed( elm ){
    if( !input ) return;

    var savedTabIndex = elm.getAttribute('tabindex')
    elm.setAttribute('tabindex', '-1')
    elm.focus()
    elm.setAttribute('tabindex', savedTabIndex)
}

// DEMO: 

var buttons = document.querySelectorAll('button'),
    input   = document.querySelector('input');

buttons[0].addEventListener('click', ()=>input.focus())
buttons[1].addEventListener('click', ()=>setFocusFixed(input))
<input placeholder='some input' tabindex='2' />
<button>Set focus on input</button>
<button>Set focus on input - fixed</button>

This little function simply sets the form field tabindex to -1 so the DOM focus() method could take affect, and immediately sets it back to its original value.

Update Aug 2019:

Seems that on Chrome 76 giving focus works as it should, without the -1 tabindex trick.


You need an attribute tabindex="0" to be able to focus (works for me) : tabindex="-1" remove the element from the page tab sequence (it is no longer focusable with keyboard for instance).

  • -1 is still focusable in some cases but not by keyboard (tab key),
  • 0 is focusable in an automatic order
  • Any other positive number defines the order to focus elements

https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-1/tabs.html

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex


Maybe you have devtools open. I just came across this and when I closed devtools everything worked fine.


Once you submit the form, any focus becomes irrelevant. The document changes location to the form's action and the focus is lost anyway.

Looks like you want to set focus after the submit, in this case do it in the onload event:

window.onload = function WindowLoad(evt) {
   byId("nav_container").focus();
}

As mentioned by others, if "nav_container" is not input box it won't work either and to scroll to that position use named anchor instead.. add such anchor before the element:

<a name="nav_container_anchor" />

Then have such JS code to scroll to that location:

document.location = "#nav_container_anchor";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜