简体   繁体   中英

Javascript change target element of keydown / keypress event

I have a div that picking up a keydown event, once fired I would like to change focus to an input field for the user to enter text. The input field is hidden until keydown.

I would like to somehow prevent the default keydown event, change the event target to the input element, then fire it again inserting the typed value into input.

Is there a way to change the keydown event element before having it fire?


The other way would be to interpret the initial keystroke and enter that as a value for the input element then focus for the remaining input. Which is a little messier but may be necessary.


https://jsfiddle.net/fr5xrsyd/4/

 $('.focus').keydown(function(e){ $('input').addClass('keydown'); e.preventDefault(); e.target = $('input')[0]; //fire event after target changed }); 
 .container { position: relative; } .focus { border: 2px solid blue; text-align: center; padding: 0.5em; z-index:1 } .focus:focus { border: 2px solid red; } input { width: 100%; height: 100%; z-index: 2; position: absolute; top: 0; left: 0; text-align: center; display: none; } input.keydown { display: inline-block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="focus" tabIndex="-1"> Click me and type a value. </div> <input placeholder="typed value should appear here"/> </div> 

$('input').focus() does the trick as per prasad's comment above.

 $('.focus').keydown(function(e){ $('input').addClass('keydown'); $('input').focus(); }); 
 .container { position: relative; } .focus { border: 2px solid blue; text-align: center; padding: 0.5em; z-index:1 } .focus:focus { border: 2px solid red; } input { width: 100%; height: 100%; z-index: 2; position: absolute; top: 0; left: 0; text-align: center; display: none; } input.keydown { display: inline-block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="focus" tabIndex="-1"> Click me and type a value. </div> <input placeholder="typed value should appear here"/> </div> 

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