Set keyboard focus to a

后端 未结 7 1837
不思量自难忘°
不思量自难忘° 2020-11-27 15:07

I have the following code snippet:

相关标签:
7条回答
  • 2020-11-27 15:22

    You could use getElementsByClassName

    <div tabindex="0" class="to-focus">TEXT</div>
    <script> document.getElementsByClassName('to-focus')[0].focus()</script>
    
    0 讨论(0)
  • 2020-11-27 15:24

    Are you in control of the asp function? If yes, then that'd be the easiest place to set focus. Otherwise, you could listen to DOMNodeInserted event (note: browser support may vary) and set focus to div (or its children) based on appropriate conditions.

    0 讨论(0)
  • 2020-11-27 15:27

    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/

    0 讨论(0)
  • 2020-11-27 15:30

    do you mean you want to focus the divs whenever it is generated? try reasearching for these

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

    and

    http://api.jquery.com/live/

    and for the keypress..

    http://api.jquery.com/keypress/

    afaik divs and other elements can have focus of some sort like in wikis, like..

    http://en.wikipedia.org/wiki/JavaScript#Cross-site_vulnerabilities

    and it'll scroll automatically there. I am just no sure how.

    as for the dynamically generated divs and tables you can use jquery's live() function

    0 讨论(0)
  • 2020-11-27 15:33

    The function that's dynamically generating the divs will have the context available to know which div to focus on, after the last div output a script with a scrollTo() to focus on the div you want. Assign each div an ID, so you'll be able to choose it out of the set.

    Response.Write "
    <script language='text/javascript'>
    document.getElementById('div#').scrollIntoView();
    </script>
    "
    
    0 讨论(0)
  • 2020-11-27 15:43

    I solve that doing the next:

    <div tabindex="0" >
        <button onclick="element.parentNode.focus();"/>
    </div>
    
    0 讨论(0)
提交回复
热议问题