最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selecting text with mouse and highlighting the same text with multiple occurences in that div - Stack Overflow

programmeradmin5浏览0评论

I am trying to code a program in which when i select a text inside a div on mouse up i want to highlight all the occurrence of the selected text in that div what i have done till now

Highlights the selected text anywhere in that div

But this works with only static i.e hardcoded words as shown in the demo like this

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

here Ipsum is hardcorded and it works fine .What i am trying to do is replace ipsum with dynamically selected text which fails.I have added the demo with what i have reached till now and the code is give below 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;
}

I am trying to code a program in which when i select a text inside a div on mouse up i want to highlight all the occurrence of the selected text in that div what i have done till now

Highlights the selected text anywhere in that div

But this works with only static i.e hardcoded words as shown in the demo like this

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

here Ipsum is hardcorded and it works fine .What i am trying to do is replace ipsum with dynamically selected text which fails.I have added the demo with what i have reached till now and the code is give below 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;
}
Share Improve this question edited Jun 2, 2014 at 20:53 balpha 51k18 gold badges113 silver badges132 bronze badges asked May 27, 2014 at 5:15 codefreaKcodefreaK 3,6627 gold badges37 silver badges65 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

DEMO

I am getting the selected text value using this function

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;
}

Then i am using using this script to highlight the 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);
    });
}

Since this is a function you can use it for any div you want to respond to highlighting.

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>

Using contenteditable and execCommand.

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>

发布评论

评论列表(0)

  1. 暂无评论