In ContentEditable, how can I get a reference to t

2019-06-07 23:55发布

问题:

I am trying to write a function that will, on keyup, give me a reference to the element immediately preceding the caret in a contentEditable div.

If the caret is in a text node then the function should return null. If the caret is at the start of the contentEditable then the function should return null.

But if the caret is at the start of a text node, and this text node is immediately preceded by an element such as a Span, then the function should return a reference to this element.

And, if the caret is placed between two Html elements (e.g. between two Spans), then it should return a reference to the element which immediately precedes the caret, i.e the first of the two elements.

If there are two or more text nodes which immediately follow one another, then they should be considered as a single text node.

I've started to cobble something together. I'm considering using range offsets to work out how far into a text node I am, but it feels overly complicated. I can't help thinking there's something obvious I'm not thinking of.

回答1:

This can be done using anchor node . Anchor node is the node upon which the cursor is positioned.we can get the element preceding it using previousSibling property .Here is how we can do it

 var selection
 if (window.getSelection)
  selection = window.getSelection();
 else if (document.selection && document.selection.type != "Control")
  selection = document.selection;

var anchor_node = selection.anchorNode; //current node on which cursor is positioned
var previous_node = anchor_node.previousSibling;
var next_node = anchor_node.nextSibling;

previous_node.nodeName will be '#text' for a textnode , 'span' for a span node.This is similar for next_node too.You can now play with these and code for your requirement.