Html input, always in focus

后端 未结 4 1596
梦谈多话
梦谈多话 2021-01-11 19:14

How can I keep the html input always in focus? Using the autofocus attribute when creating the element helps to focus at pageload, but it does not keep the focu

相关标签:
4条回答
  • 2021-01-11 19:36

    For FIREFOX, Try using setTimeOut, it works :

    My JS :

    myFocusFunction(){
          let myInput = document.getElementById('idOfInput');
          setTimeout(function() { 
               myInput .focus(); 
          }, 100);
    }
    

    my Html :

    <input type="text" ng-blur="myFocusFunction()" auto-focus >
    
    0 讨论(0)
  • 2021-01-11 19:40

    What worked for me was using the autofocus attribute on the HTML input to focus it on initial page load, and then disabling all mousedown events:

    document.onmousedown = (e) => {
      e.preventDefault();
    }
    

    Obviously if you need to support mouse events, you'd want a less drastic approach, but it fit my use case for a command-line emulator web app.

    0 讨论(0)
  • 2021-01-11 19:45

    Try this:

    <!-- On blur event (unfocus) refocus the input -->
    <input onblur="this.focus()" autofocus /> 
    <input value="Can't focus on this" />

    Basically, you add a blur event (which occurs whenever the input loses focus), and in the blur event, you focus on the input. In addition, you add the autofocus attribute to start off focused as well.

    P.S. If you are planning to use this for a website for actual people to use, from a user interface perspective, this is probably not a great idea.

    0 讨论(0)
  • 2021-01-11 19:49

    For react and the like:

    <input  type={'text'}  autoFocus={true} onBlur={({ target }) => target.focus()}/>
    
    0 讨论(0)
提交回复
热议问题