简体   繁体   中英

setting cursor position in span in div is not working

I have a contenteditable div with a span in-between:

<div id="textArea" contenteditable><span style="font-size: 1em; font-family: Arial; text-align: left"></span></div>

I would like to set the cursor in-between:

left">

and

</span>

I use the following code:

                      var textArea = document.getElementById("textArea");

                      textArea.onfocus = function(event){
                          var range = document.createRange();
                          var node = textArea.fistChild;
                          range.setStart(node.childNodes[0], 67);
                          var sel = window.getSelection();
                          range.collapse(true);
                          sel.removeAllRanges();
                          sel.addRange(range);
                          textArea.focus();
                      }

Unfortunately, this code only works when there is something written in-between the span at the beginning.

Can somebody please help me out?

Thank you very much, Lucas

One way you can do this is by adding a sim &nbsp; to your HTML:

<div id="textArea" contenteditable><span style="font-size: 1em; font-family: Arial; text-align: left">&nbsp;</span></div>

It might not look like the prettiest solution, but it works. Look at the jsfiddle .

This will add a blank space first

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