我正在尝试创建jquery,它允许通过鼠标突出显示所选文本,包括几个选择(例如三个单独的部分)。目前我有the following code,但在此代码中遇到了以下问题:
请告知我如何改进此脚本以解决上述问题。 谢谢!
js代码:
enableHighlights(".mainPane");
function enableHighlights(thisDiv) {
$(thisDiv).on("mouseup", function () {
var selectedText = getSelectionText();
var selectedTextRegExp = new RegExp(selectedText);
var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>");
$(this).html(text);
$('#selection').html(selectedText);
});
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().htmlText;
}
return text;
}
答案 0 :(得分:0)
这是我能得到正确答案的最接近的结果: DEMO
enableHighlights(".mainPane");
var sText=[],
sStart=[];
function enableHighlights(thisDiv) {
var initialHTML=$(thisDiv).html();
var theHTML='';
$(thisDiv).on("mouseup", function () {
var selectedText = getSelectionText();
var selectedRange=getSelectionRange($(thisDiv)[0]);
sText.push(selectedText);
sStart.push(selectedRange.start);
theHTML=initialHTML;
$.each(sText,function(i,v){
var selectedTextRegExp = new RegExp(v);
var usingHTML=theHTML.slice(sStart[i]-1);
var text = usingHTML.replace(selectedTextRegExp, "<span class='red'>" + v + "</span>");
theHTML=theHTML.slice(0,sStart[i]-1)+text;
});
$(this).html(theHTML);
$('#selection').html(selectedText);
});
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().htmlText;
}
return text;
}
function getSelectionRange(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != "undefined") {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != "undefined" &&
(sel = document.selection).type != "Control") {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint("EndToStart", range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end
};
}
唯一的问题是,当您尝试一起选择粗体和普通文本时,我无法找到解决方法!