apply使用javascript中的高亮显示HTML文本,如Microsoft Word中所示

时间:2012-09-27 08:48:14

标签: javascript jquery

我有以下代码用于使用javascript突出显示html文本:

var counter = 1;
function BindEventForHighlight() {
   $('#ParaFontSize').bind("mouseup", HighlightText);
   $('#ParaFontSize').unbind("mouseup", RemoveHighlight);
}


function UnBindHighlightEvent() {
   $('#ParaFontSize').bind("mouseup", RemoveHighlight);
   $('#ParaFontSize').unbind("mouseup", HighlightText);
}


function HighlightText() {

   var text = window.getSelection();
   var start = text.anchorOffset;
   var end = text.focusOffset - text.anchorOffset; 

   range = window.getSelection().getRangeAt(0);
   range1 = window.getSelection().toString();
   var selectionContents = range.extractContents();
   var span = document.createElement("span");

   span.appendChild(selectionContents);

   span.setAttribute("id", counter);
   span.setAttribute("class", "highlight");
   range.insertNode(span);
   counter++;

}

function RemoveAllHighlights() {
  var selection = document.getElementById('ParaFontSize');
  var spans = selection.getElementsByTagName("span");
  for (var i = 0; i < spans.length; i++) {
      spans[i].className = ""; 
  }
}

function RemoveHighlight() {
   var selection = window.getSelection();
  if (selection.toString() !== "" &&
           selection.anchorNode.parentNode.nodeName === "SPAN") {
     selection.anchorNode.parentNode.className = "";
  }
  else {
     return false;
  }
}

HighlightText函数使用范围对象突出显示文本。我想将所选文本的开头和结尾保存到数据库中,当用户返回同一页面时,他将看到上一次突出显示的文本。我还想要其他场景如下:

  1. 当用户突出显示某些文字时,他将能够取消全部或部分突出显示的文本,并保留其余文字。

  2. 用户可以清除页面中所有突出显示的文字。

  3. 让我说我希望这种荧光笔功能成为MS字中的荧光笔。

    提前致谢 真的很感激。

0 个答案:

没有答案