突出显示用户选择的文本片段 [英] Highlight text fragment selected by user

查看:68
本文介绍了突出显示用户选择的文本片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有< div>带有一些文字< div> ,我需要突出显示用户选择的文字片段。



我已经部分实现了这个:


  1. 当用户选择全文时,它不会突出显示,但是仍然被选中。


  1. 如何为移动设备实现此功能?问题是没有触发 mouseup 事件。


解决方案

更新



选择& Range API



以下演示使用以下内容:


选择API

.getSelection()

.getRangeAt()

范围API

.extractContents()

.insertNode()

其他

.createElement()

.appendChild()

.ctrlKey

.textContent

.tagName

.parentNode

< a href =https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild =nofollow noreferrer> .removeChild()

.createTextNode()


只需选择文字,它就会在所选文字周围打上< mark> 标记。要删除突出显示,请单击 + ctrl (Mac:单击 + 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(节点); sel.removeAllRanges();函数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 + keyupdocument.addEventListener('mouseup',mark); // ctrl + mouseupdocument.addEventListener('click',unmark); // alt +单击 

  :: 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 repreptderit 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



尝试使用伪元素 ::选择






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


I have a <div>with some text<div> and I need to highlight the text fragment selected by a user.

I've partly implemented this: 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>

However, I'm stuck with solving following problems:

  1. I need to highlight the exact fragment selected by user even if there a multiple matches in the text. For example, if user selects the second letter t in the <div>with some text<div>, only that t should be highlighted, not all of them or the first one.

  1. When user select the full text, it is not highlighted, but remains selected.

  1. How do I implement this for mobile? The problem is the mouseup event is not triggered.

解决方案

Update

Selection & Range API

The following demo uses the following:

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

Just select text and it will wrap a <mark> tag around the selected text. To remove the highlight click + ctrl (Mac: click + control)


Demo 1

Selection and Range 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

Try the pseudo-element ::selection


Demo 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>

这篇关于突出显示用户选择的文本片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆