在contentEditable元素中插入HTML元素 [英] Insert an HTML element in a contentEditable element
问题描述
我有一个contentEditable div,我想在其中插入HTML标签(一个简单的span元素).
I have a contentEditable div where I want to insert HTML tags (a simple span element).
是否有一个跨浏览器解决方案,允许我在div选择或光标位置上插入这些标签.如果在页面上选择了其他内容(而不是在div中),我想将标签附加到div的末尾.
Is there a cross browser solution that allows me to insert those tags over my div selection or cursor position. If something else is selected on the page (not in the div), I want to append the tag to the end of the div.
谢谢
推荐答案
这是一个好机会
// get the selection range (or cursor position)
var range = window.getSelection().getRangeAt(0);
// create a span
var newElement = document.createElement('span');
newElement.id = 'myId';
newElement.innerHTML = 'Hello World!';
// if the range is in #myDiv ;)
if(range.startContainer.parentNode.id==='myDiv') {
// delete whatever is on the range
range.deleteContents();
// place your span
range.insertNode(newElement);
}
我没有IE,但可以在Firefox,Chrome和Safari浏览器上正常工作.也许您只想在contentEditable div上进行选择后,才能继续使用range.startContainer进行播放.
I don't have IE but works fine on firefox, chrome and safari. Maybe you want to play with range.startContainer to proceed only if the selection is made on the contentEditable div.
编辑:根据 quirksmode范围介绍,您必须更改窗口.getSelection()部分与IE兼容.
According to quirksmode range intro you have to change the window.getSelection() part to be IE compatible.
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
else if (document.selection) { // should come last; Opera!
userSelection = document.selection.createRange();
}
这篇关于在contentEditable元素中插入HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!