在选择之前和之后插入文本以满足要求 [英] Insert text before and after selection in a contenteditable
本文介绍了在选择之前和之后插入文本以满足要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在一个可信的div中在所选文本之前和之后插入类似于bbcode的文本?我已经看到了textarea的许多答案,但代码不适用于contenteditable div。不需要IE支持。
Is there a way to insert text similar to bbcode before and after the selected text in a contenteditable div? I've seen many answers for textarea, but the code does not work with a contenteditable div. IE support is not needed.
推荐答案
我建议的方法是:
- 从选择中获取范围
- 在范围的末尾插入文本节点
- 插入范围开头的另一个文本节点
- 重新选择原始文本
- Obtain a range from the selection
- Insert a text node at the end of the range
- Insert another text node at the start of the range
- Reselect the original text
以下演示将在所有主要浏览器中工作,除了IE< = 8。
The following demo will work in all major browsers except IE <= 8.
演示: http://jsfiddle.net/8WEru/
代码:
function surroundSelection(textBefore, textAfter) {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var startNode = range.startContainer, startOffset = range.startOffset;
var startTextNode = document.createTextNode(textBefore);
var endTextNode = document.createTextNode(textAfter);
var boundaryRange = range.cloneRange();
boundaryRange.collapse(false);
boundaryRange.insertNode(endTextNode);
boundaryRange.setStart(startNode, startOffset);
boundaryRange.collapse(true);
boundaryRange.insertNode(startTextNode);
// Reselect the original text
range.setStartAfter(startTextNode);
range.setEndBefore(endTextNode);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
这篇关于在选择之前和之后插入文本以满足要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文