How to prevent an element from losing focus?

后端 未结 6 1824
忘掉有多难
忘掉有多难 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 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:

    
    
    
    
    

提交回复
热议问题