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

标签 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事件未触发。

最佳答案

更新

Selection & Range接口(interface)

以下演示使用以下内容:

Selection API
.getSelection()
.getRangeAt()
Range API
.extractContents()
.insertNode()
Miscellaneous
.createElement()
.appendChild()
.ctrlKey
.textContent
.tagName
.parentNode
.removeChild()
.createTextNode()

只是select text + ctrl (Mac: select text + ^) 它会包裹一个<mark>标记所选文本。删除突出显示 click + alt(苹果机:click + )


演示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>

关于javascript - 突出显示用户选择的文本片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55087160/

相关文章:

javascript - 当其他选择更改时如何更改选择标签值?

JavaScript - 我如何告诉 Chrome、Firefox、Safari 浏览器允许我禁用刷新按钮?

javascript - Angular 7 - promise 内的 forEach 迭代在 promise 解决后执行。为什么?

html - 如果我在我的网站上使用 Google Web Fonts,字体会正确显示吗?

html - 在 Xcode 9 中使用 Swift 4 抓取 html

javascript - JSON 文件内容未在 HTML 中加载

javascript - ImageMap 的外坐标

javascript - 导航菜单不粘,有白色间隙

css - 动态 block 内的响应图像

php - 隐藏 sql 结果列并在单击时显示在下表中