In ContentEditable, how can I get a reference to the element immediately preceding the caret?

青春壹個敷衍的年華 提交于 2020-01-03 02:01:31

问题


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.



来源:https://stackoverflow.com/questions/14551134/in-contenteditable-how-can-i-get-a-reference-to-the-element-immediately-precedi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!