简体   繁体   中英

Not able to `focus` editable `div` element

I would like to set the focus to one of my contentEditable div element. but not working.

here is my code:

 $(document).click(function () { $('div').focus(); }); 
 div{ border:1px solid red; } 
 <div contentEditable >&nbsp;</div> 

Here is a working snippet without using jQuery (which you do not load in your snippet). I also added an ID to get the correct div .

 document.getElementById('edit-me').focus(); 
 div { border:1px solid red; } 
 <div id="edit-me" contentEditable>&nbsp;</div> 

You should wait until the entire document is loaded before executing jQuery.

 $(document).ready(function () { $('div').click(function () { $('div').focus(); }) }); 
 div{ border:1px solid red; } 
 <div contentEditable >&nbsp;</div> 

Import jquery! Yay!

 $(document).ready(function () { //I replaced "click" with "ready" because think that you want to focus once loaded, not once you click somewhere in the document. //"click" can still be used if you want to focus once you clicked somewhere in your window $('div').focus(); }); 
 div{ border:1px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div contentEditable >&nbsp;</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