How to prevent an element from losing focus?

后端 未结 6 1783
忘掉有多难
忘掉有多难 2020-12-30 01:36

How to keep the Focus on one textbox ? even if you click anywhere in a browser.

$(\"#txtSearch\").focus();
相关标签:
6条回答
  • 2020-12-30 01:47

    It's also possible without jQuery and without re-focusing, if you just need a click on specific elements to not grab the focus

    just listen for the mousedown event and cancel it

    element.addEventListener("mousedown", event => {event.preventDefault(); event.stopPropagation()});
    
    0 讨论(0)
  • 2020-12-30 01:55

    Konstantin Dinev answer works ok in most cases, but if you dont want to lose the focus only when clicking on certain parts of the html just do this:

    $(".nofocus").on( "mousedown", function (e) {
        return false;
    });
    

    In my case i'm doing a small html text editor and i dont want to lose the control when pressing an action button, but yes in any other case.

    I just need to add the nofocus class to the button and it will not take the control

    0 讨论(0)
  • 2020-12-30 02:05
    $("html").click(function(){
       $("#txtSearch").focus();
    });
    

    Live Demo: http://jsfiddle.net/QhaLY/

    0 讨论(0)
  • 2020-12-30 02:07
    $('body').click(function(){$("#txtSearch").focus();});
    
    0 讨论(0)
  • 2020-12-30 02:09

    You need to subscribe to the blur event of the textbox and reinstate focus with a small timeout:

    $('#txtSearch').blur(function (event) {
        setTimeout(function () { $("#txtSearch").focus(); }, 20);
    });
    

    This way you don't rely on subscribing to the events of any other element on the page. If you subscribe to body click or html click, it won't run if any other element prevents propagation of its click event, also it won't work when tabbing out of the textbox.

    Example:

    <!-- I will not propagate my click to top level DOM elements -->
    <button id="button">Click me</button>
    
    <script>
    $('#button').click(function (event) {
        event.stopPropagation();
    });
    </script>
    
    0 讨论(0)
  • 2020-12-30 02:10

    There are other ways of loosing focus than clicking area away from the input i.e. tabbing. If you want to prevent loosing focus use blur event i.e.

    document.getElementById('txtSearch').addEventListener('blur', e => {
      e.target.focus();
    });

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