突出显示用户选择的文本片段

时间:2019-03-10 11:23:12

标签: javascript html

我有一个<div>with some text<div>,我需要突出显示用户选择的文本片段。

我已经部分实施了此操作: here is my code

thisRespondHightlightText(".container");


function thisRespondHightlightText(thisDiv){
    $(thisDiv).on("mouseup", function () {
        var selectedText = getSelectionText();
        var selectedTextRegExp = new RegExp(selectedText,"g");
        var text = $(this).text().replace(selectedTextRegExp, "<span class='highlight'>" + selectedText + "</span>");
        $(this).html(text);
    });
}

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}
.highlight {
    background-color: orange;
}
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>

但是,我坚持解决以下问题:

  1. 即使文本中有多个匹配项,我也需要突出显示用户选择的确切片段。例如,如果用户在t中选择第二个字母<div>with some text<div>,则仅应突出显示t,而不是所有字母或第一个字母。

issue1

  1. 当用户选择全文时,它不会突出显示,而是保持选中状态。

issue2

  1. 如何在移动设备上实现此功能?问题是mouseup事件未触发。

1 个答案:

答案 0 :(得分:3)

更新

SelectionRange API

以下演示使用以下内容:

  

选择API
  .getSelection()
  .getRangeAt()
  范围API
  .extractContents()
  .insertNode()
  其他
  .createElement()
  .appendChild()
  .ctrlKey
  .textContent
  .tagName
  .parentNode
  .removeChild()
  .createTextNode()

只需选择文本,它将在所选文本周围包裹一个<mark>标签。删除突出显示的click + ctrl (Mac:click + control


演示1

选择和范围API

function mark(e) {
  if (e.ctrlKey) {
    var sel = document.getSelection();
    var rng = sel.getRangeAt(0);
    var cnt = rng.extractContents();
    var node = document.createElement('MARK');
    node.style.backgroundColor = "orange";
    node.appendChild(cnt);
    rng.insertNode(node);
    sel.removeAllRanges();
  }
}

function unmark(e) {
  var cur = e.currentTarget;
  var tgt = e.target;
  if (tgt.tagName === 'MARK') {
    if (e.altKey) {
      var txt = tgt.textContent;
      tgt.parentNode.replaceChild(document.createTextNode(txt), tgt);
    }
  }
  cur.normalize();
}

document.addEventListener('keyup', mark); // ctrl+keyup
document.addEventListener('mouseup', mark);// ctrl+mouseup
document.addEventListener('click', unmark); // alt+click
::selection {
  background: orange
}
<P>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</P>


::selection

尝试使用伪元素::selection


演示2

::selection {
  background: orange;
}
<P>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</P>