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

前端 未结 8 1504
说谎
说谎 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:25
    window.location.hash = '#tries';
    

    This will scroll to the element in question, essentially "focus"ing it.

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

    document.getElementById('tries').scrollIntoView() works. This works better than window.location.hash when you have fixed positioning.

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

    You can use tabindex

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

    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.
    0 讨论(0)
  • 2020-11-22 14:46
    <div id="inner" tabindex="0">
        this div can now have focus and receive keyboard events
    </div>
    
    0 讨论(0)
  • 2020-11-22 14:48

    I wanted to suggest something like Michael Shimmin's but without hardcoding things like the element, or the CSS that is applied to it.

    I'm only using jQuery for add/remove class, if you don't want to use jquery, you just need a replacement for add/removeClass

    --Javascript

    function highlight(el, durationMs) { 
      el = $(el);
      el.addClass('highlighted');
      setTimeout(function() {
        el.removeClass('highlighted')
      }, durationMs || 1000);
    }
    
    highlight(document.getElementById('tries'));
    

    --CSS

    #tries {
        border: 1px solid gray;
    }
    
    #tries.highlighted {
        border: 3px solid red;
    }
    
    0 讨论(0)
  • 2020-11-22 14:48

    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>

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