使用鼠标选择文本并突出显示该div中多次出现的相同文本

时间:2014-05-27 05:15:38

标签: javascript jquery css regex

我正在尝试编写一个程序,当我在鼠标中选择div内的文本时,我想突出显示该div中所选文本的所有出现,直到现在我已经完成了

Highlights the selected text anywhere in that div

但这只适用于静态,即硬编码的单词,如演示中所示 像这样

 var text = $('div').text().replace(/Ipsum/g,"<span class='red'>Ipsum</span>");

这里的Ipsum很硬,而且工作正常。我想做的是用动态选择的文本替换ipsum失败。我已经添加了演示到目前为止已经达到的并且代码在下面给出 Demo getting selected text dynamically on mouseup

HTML

<div id="div">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>

<input type="button" value="Click to remove highlight" id="id2" />

Jquery的

$("div").mouseup(function(){
  $(this).after("Mouse button released.");
              var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    } var textspan ="<span class='red'>"+text+'</span>';
        var text1 = $('div').text().replace('/'+text+'/g',textspan);
        alert(text);
          alert(textspan);
            alert(text1);
$('div').html(text1);
});





$('#id2').click(
  function(){
      $( "span.red" ).each(function() {
  $( this ).contents().unwrap();

});

    }
);

的CSS

.red {
color: red;
}

2 个答案:

答案 0 :(得分:1)

DEMO

我使用此功能

获取所选文本
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

然后我使用此脚本突出显示文本

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

由于这是一项功能,您可以将其用于任何 div,以响应突出显示

thisRespondHightlightText(".select--highlight--active");

<强> HTML:

<div class="select--highlight--active">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 :(得分:0)

使用contenteditableexecCommand

onmouseup = (function(){
  document.execCommand("backColor", false, "chartreuse")
  window.getSelection().removeAllRanges()
})
<div contenteditable>
In mathematics, extrapolation is the process of estimating, beyond the original observation range, the value of a variable on the basis of its relationship with another variable. It is similar to interpolation, which produces estimates between known observations, but extrapolation is subject to greater uncertainty and a higher risk of producing meaningless results. Extrapolation may also mean extension of a method, assuming similar methods will be applicable. Extrapolation may also apply to human 
</div>