2012-05-11 28 views
0

使用下面的XHTML代码...JavaScript的:插入在键盘插入符号图像元素旁边现有的图像元素

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

...如果用户有键盘插入符号只图像元素后(无论是anchorNode或focusNode)我想使用一个W3C标准方法,例如appendChild或insertBefore插入一个新的图像元素。

我已尝试以下步骤来确定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)没有使用专有的微软内部---什么方法。

2)没有使用框架,不仅仅是因为它们使用内部---任何方法。我试图确定一个图像元素是否恰好位于插入符号旁边,如果是文本,那么这是一个不同的条件(只要提到{alert('in或next next to text');});});}) 。

回答

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