突出显示div标签内给定位置的文本

时间:2017-07-26 06:16:59

标签: javascript jquery text selection highlight

我已使用以下代码获得所选单词的位置:

function getSelectionCharOffsetsWithin(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 - 1;

  } else if (typeof document.selection != "undefined" &&
    (sel = document.selection).type != "Control") {
    range = sel.createRange();
    alert(range);
    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
  }
}

function alertSelection() {
  var mainDiv = document.getElementById("myclass");
  var sel = getSelectionCharOffsetsWithin(mainDiv);
  alert(sel.start + ": " + sel.end);
}
<div id="myclass" onmouseup="alertSelection()">
  <p>This is highlight text demo.</p>
</div>

我想要的是在html文本中突出显示该位置的文本。我给文本的位置必须在内容中突出显示。如果用户刷新页面,它不应该消失。

0 个答案:

没有答案