contenteditable put caret outside inserted span

2019-01-20 01:36发布

问题:

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.

回答1:

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:

  • Setting the caret position to an empty node inside a contentEditable element
  • https://stackoverflow.com/a/15814297/96100
  • Placing caret outside of inserted tag in ContentEditable
  • Setting the caret position to an empty node inside a contentEditable element

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



回答2:

This is an old post, and this is part of the solution to the problem. There are more complex approaches I haven't finished working out, but simple is always good.

const editor = document.querySelector('[contenteditable="true"]');
const spans = document.querySelectorAll('span[contenteditable="false"]');

Array.prototype.slice.call(spans).map(span => {
  const empty = document.createTextNode( '\uFEFF' );
  const parentEl = span.parentElement;
  const allchildnodes = editor.childNodes;
  const lastsib = allchildnodes[allchildnodes.length - 1];
  const ended = lastsib.wholeText === '\n';
  const prevsib = ended ? lastsib.previousSibling === span : false;
  if (prevsib) {
    parentEl.appendChild(empty);
  }
}); 

https://codepen.io/augur/pen/MvaKJO