Is it possible to focus on a
using JavaScript focus() function?

前端 未结 8 1477
说谎
说谎 2020-11-22 14:21

Is it possible to focus on a

using JavaScript focus() function?

I have a

tag

相关标签:
8条回答
  • 2020-11-22 14:48

    To make the border flash you can do this:

    function focusTries() {
        document.getElementById('tries').style.border = 'solid 1px #ff0000;'
        setTimeout ( clearBorder(), 1000 );
    }
    
    function clearBorder() {
        document.getElementById('tries').style.border = '';
    }
    

    This will make the border solid red for 1 second then remove it again.

    0 讨论(0)
  • 2020-11-22 14:51

    Yes - this is possible. In order to do it, you need to assign a tabindex...

    <div tabindex="0">Hello World</div>
    

    A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

    You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

    document.getElementById('test').onclick = function () {
        document.getElementById('scripted').focus();
    };
    div:focus {
        background-color: Aqua;
    }
    <div>Element X (not focusable)</div>
    <div tabindex="0">Element Y (user or script focusable)</div>
    <div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>
    <div id="test">Set Focus To Element Z</div>

    Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.

    0 讨论(0)
提交回复
热议问题