Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - contenteditable put caret outside inserted span

http://jsfiddle.net/VzbYJ/86/

Please have a look at this link. As it clears that it is going to insert a span node at the caret place. Problem is,after inserting the node if I am pressing any character its color is also green. because it is also coming inside the span element. So how can I put the caret after the span so that the color of next inserted node remains normal.

I tried to find the selected node (based on to caret position), set the range after the element and used collapse(false). But I could not get the desired output.

Code for find the node :

  function findNode(event)
  {
    if (event.type == 'click')
    par = event.target;

    else if (event.type == 'keyup'){        
        if (document.selection)
        par = document.selection.createRange().parentElement();
    else if (window.getSelection){
        var range = window.getSelection().getRangeAt(0);
        par = range.commonAncestorContainer.parentNode;
    }
  }

and next I set the boundary using setEndAfter() ant collapse(false). I am new in this field so I am not sure that what extend I am right. So any suggestion is very much appreciable. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A quick look at the "Related" section on this very page will give you links to all the information you need. In summary, the browser (unless it's Firefox) prevents it and the easiest workaround is to insert a zero-width space character (Unicode U+200B) after the inserted <span> element. As well as being a very ugly hack, this does have the problem of keeping track of and removing these zero-width spaces once they're no longer required.

I've updated your jsFiddle to use this approach but without any code to remove the zero-width spaces:

http://jsfiddle.net/VzbYJ/87/

For background, here's a list of relevant questions/answers:

I need a stock answer for this, it comes up so often...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...