JavaScript:在键盘插入符号处插入现有图像元素旁边的图像元素



使用以下 XHTML 代码...

<div contenteditable="true">
<img alt="" src="1.png" />
</div>

。如果用户在图像元素(锚节点或焦点节点)之后有键盘插入符号,我想使用 W3C 标准方法(如 appendChild 或 insertBefore)插入新的图像元素。

我已经尝试了以下方法来确定 DOM 中的位置...

alert(
'focusNode = '+window.getSelection().focusNode
+'nnpreviousSibling = '+window.getSelection().focusNode.previousSibling
+'nnnextSibling = '+window.getSelection().focusNode.nextSibling
+'nnparentNode = '+window.getSelection().focusNode.parentNode);
try
{
alert(
'focusNode = '+window.getSelection().focusNode
+'nn.previousSibling.previousSibling = '+window.getSelection().focusNode.previousSibling.previousSibling
+'nn.nextSibling.nextSibling = '+window.getSelection().focusNode.nextSibling.nextSibling
+'nnparentNode = '+window.getSelection().focusNode.parentNode);
} catch (err) {}
alert(
'anchorNode = '+window.getSelection().anchorNode
+'nnpreviousSibling = '+window.getSelection().anchorNode.previousSibling
+'nnnextSibling = '+window.getSelection().anchorNode.nextSibling
+'nnparentNode = '+window.getSelection().anchorNode.parentNode);
try
{
alert(
'anchorNode = '+window.getSelection().anchorNode
+'nn.previousSibling.previousSibling = '+window.getSelection().anchorNode.previousSibling.previousSibling
+'nn.nextSibling.nextSibling = '+window.getSelection().anchorNode.nextSibling.nextSibling
+'nnparentNode = '+window.getSelection().anchorNode.parentNode);
} catch (err) {}

我也尝试过这个,它只是告诉我有多少空格字符(隔行)......

alert(window.getSelection().anchorOffset+'nn'+window.getSelection().focusOffset);

我无法确定如何直接在键盘插入符号旁边找到图像。


我的目标是仅使用 W3C 方法和属性来执行此操作。

1.)不使用专有Microsoft内部---任何方法。

2.)不使用框架,不仅仅是因为他们使用内部---任何东西的方法。

3.) 我正在尝试确定图像元素是否就在插入符号旁边,如果是文本,那么这是一个不同的条件(只需提及 {alert('in or next to text');})。

var img = document.createElement('img');
img.setAttribute('alt','alternative text');
img.setAttribute('src','2.png');
window.getSelection().getRangeAt(0).insertNode(img);

最新更新