在ContentEditable中,如何获得对插入符号之前紧邻的元素的引用? [英] In ContentEditable, how can I get a reference to the element immediately preceding the caret?

查看:224
本文介绍了在ContentEditable中,如何获得对插入符号之前紧邻的元素的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数将在keyup上给我一个对contentEditable div中插入符号前面的元素的引用.

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.

如果插入符号在文本节点中,则该函数应返回null.如果插入符号位于contentEditable的开头,则该函数应返回null.

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.

但是,如果插入标记位于文本节点的开头,并且此文本节点紧跟在诸如Span之类的元素之前,则该函数应返回对该元素的引用.

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.

并且,如果插入符号位于两个HTML元素之间(例如,两个Span之间),则它应返回对插入符号之前紧接的元素(即两个元素中的第一个元素)的引用.

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.

推荐答案

可以使用锚点节点完成此操作.锚点节点是光标所在的节点.我们可以使用previousSibling属性获取其前面的元素.这是我们可以做到的方法

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对于textnode来说是'#text',对于span节点来说是'span'.对于next_node也是如此.您现在可以使用这些代码并根据需要进行编码了.

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.

这篇关于在ContentEditable中,如何获得对插入符号之前紧邻的元素的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆