简体   繁体   中英

Prevent mousedown from stealing focus of current input but allow text selection

Is it possible to prevent a mousedown in a div to steal focus, but allow text selection in this container (eg <div> )?

 /*// Version #1: Focus kept, but text is not selectable $('div').on('mousedown', function(event) { event.preventDefault(); }); /**/ // Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state) $('div').on('mousedown', function(event) { window.setTimeout( function() { $('input').focus(); }, 1 ); }); /**/ $('input').focus(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" /> <div>A div container with some text, that should be selectable but not stealing focus of the input field</div> 

My second version flickers, when just clicking the text (tested in current Chrome). In Firefox the selection always starts at the input field. Is there any better solution?

The answer is right in front of your eyes :)

 /*// Version #1: Focus kept, but text is not selectable $('div').on('mousedown', function(event) { event.preventDefault(); }); /**/ // Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state) $('input').on('focusout', function(event) { //setTimeout(function(){$('input').focus()}, 1); }); /**/ //$('div').on('mouseup', function(event) { // $('input').focus(); //}); $('html').on('mouseup', function(event) { $('input').focus(); }); $('input').focus(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" /> <div>A div container with some text, that should be selectable but not stealing focus of the input field</div> 

The issue that if your mouseup happens outside this div , the focus is lost will persist.

Another approach would be to bind the mouseup even on the html , though this sounds a little excessive IMO, but seems to work.

The problem is that if you want focus to return to the input checkbox, you'll need to use the focusout event, shown in the snippet. The other paradigm of "keeping" focus on the input box wouldn't work, because Javascript is synchronous and only one thing can run at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM