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

时间:2012-05-11 11:38:42

标签: javascript dom

使用以下XHTML代码......

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

...如果用户在图像元素(anchorNode或focusNode)之后有键盘插入符号,我想使用诸如appendChild或insertBefore之类的W3C标准方法来插入新的图像元素。

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

alert(
'focusNode = '+window.getSelection().focusNode
+'\n\npreviousSibling = '+window.getSelection().focusNode.previousSibling
+'\n\nnextSibling = '+window.getSelection().focusNode.nextSibling
+'\n\nparentNode = '+window.getSelection().focusNode.parentNode);

try
{
alert(
'focusNode = '+window.getSelection().focusNode
+'\n\n.previousSibling.previousSibling = '+window.getSelection().focusNode.previousSibling.previousSibling
+'\n\n.nextSibling.nextSibling = '+window.getSelection().focusNode.nextSibling.nextSibling
+'\n\nparentNode = '+window.getSelection().focusNode.parentNode);
} catch (err) {}

alert(
'anchorNode = '+window.getSelection().anchorNode
+'\n\npreviousSibling = '+window.getSelection().anchorNode.previousSibling
+'\n\nnextSibling = '+window.getSelection().anchorNode.nextSibling
+'\n\nparentNode = '+window.getSelection().anchorNode.parentNode);

try
{
alert(
'anchorNode = '+window.getSelection().anchorNode
+'\n\n.previousSibling.previousSibling = '+window.getSelection().anchorNode.previousSibling.previousSibling
+'\n\n.nextSibling.nextSibling = '+window.getSelection().anchorNode.nextSibling.nextSibling
+'\n\nparentNode = '+window.getSelection().anchorNode.parentNode);
} catch (err) {}

我也尝试了这个,只是告诉我有多少个空白字符(断裂线)......

alert(window.getSelection().anchorOffset+'\n\n'+window.getSelection().focusOffset);

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


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

1。)没有使用专有的Microsoft内部---任何方法。

2。)没有使用框架而不仅仅是因为它们使用内部---任何方法。

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

1 个答案:

答案 0 :(得分:0)

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