Autofocus to a div so we can use arrow keys to scroll without having to click first

后端 未结 4 1475
你的背包
你的背包 2021-01-06 06:57

I have a page with a few

containers.

How to give focus to one of them on page load, so that the user can use arrow keys to scroll (or even

4条回答
  •  再見小時候
    2021-01-06 07:15

    You need, first of all, to add a tabindex="-1" to div#main to make it programmatically focusable. Then with javascript get the div and make it focused.

    Here's a snippet: make sure to add the code in window.onload event or to put your script tag directly before

    HTML: add tabindex attribute to div#main

    JavaScript: make div#main focused

    document.getElementById("main").focus();
    

    With that it will be automatically focused and still accept click event if you need to do some stuff when clicked, clean!

    Hope I was able to put you further.

提交回复
热议问题