我有一些文字,我可以在选择之前和之后添加我的文字:
Hello, I can insert text before and after this by javascript.
1. How to insert text
2. before each line
a. if text is separeted by /g
对于环绕声选择我正在使用此代码:
function surroundSelection(textBefore, textAfter, color) {
if (window.getSelection) {
var sel = window.getSelection();
var selectedText = sel.toString();
if(selectedText.trim() != "") {
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var startNode = range.startContainer, startOffset = range.startOffset;
var startTextNode = document.createElement(\'span\');
startTextNode.style.backgroundColor = color;
var startTextNode_t = document.createTextNode(textBefore);
startTextNode.appendChild(startTextNode_t);
var endTextNode = document.createElement(\'span\');
endTextNode.style.backgroundColor = color;
var endTextNode_t = document.createTextNode(textAfter);
endTextNode.appendChild(endTextNode_t);
var boundaryRange = range.cloneRange();
boundaryRange.collapse(false);
boundaryRange.insertNode(endTextNode);
boundaryRange.setStart(startNode, startOffset);
boundaryRange.collapse(true);
boundaryRange.insertNode(startTextNode);
range.setStartAfter(startTextNode);
range.setEndBefore(endTextNode);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
}
选择文字后的结果可以是:
**!!its_my_text_start!!**Hello, I can insert text before and after this by javascript.
1. How to insert text
2. before each line **!!its_my_text_end!!**
a. if text is separeted by /g
但现在我需要选择列表的文本,并将我的文本放在每个元素的开头和结尾处,由/ g分隔。
例如:
Hello, I can insert text before and after this by javascript.
**El_1_start** 1. How to insert text **El_1_end**
**El_2_start** 2. before each line **El_2_end**
**El_3_start** a. if text is separeted by /g **El_3_end**
如何使用window.getSelection?
执行此操作