2011-06-13 30 views
3

所選文本的第n個位置,我下面的div:更換使用jQuery

<div id="target" >hello(first), hello(second), hello(third), hello(fourth)</div> 

和下面的代碼在此基礎上discussion

$(document).ready(function(){ 
     $('#target').bind('mouseup', function(){ 
      var needle = window 
      .getSelection() 
      .getRangeAt(0); 
      var haystack = $(this).text(); 
      var newText = haystack.replace(needle,'<span class="highlight">' + needle + '</span>'); 
      $(this).html(newText);    
     }); 

當我選擇其中的「你好「,它」隨機「突出顯示其中一個,而不是實際選定的」hello「。

如何突出顯示選定的一個?

在此先感謝您的幫助。

回答

1

這裏有一些東西,似乎運作良好:

$('#target').bind('mouseup', function(){ 
    var needle = window.getSelection().getRangeAt(0); 
    var start = window.getSelection().anchorOffset; 
    var end = window.getSelection().focusOffset; 
    var haystack = $(this).text(); 
    var startHighlight = '<span class="highlight">'; 
    var endHighlight = '</span>'; 
    var nodeContent = window.getSelection().anchorNode.textContent; 

    // If the selection goes backward, switch indexes 
    if (end < start) 
    { 
     var tmp = start; 
     start = end; 
     end = tmp; 
    } 

    // If there is a span 
    if ($('span', this).size() > 0) 
    { 
     // If the selection starts after the span, compute an offset for start and end 
     if (haystack.substr(0, nodeContent.length) != nodeContent) 
     { 
      var diff = $(this).html().indexOf(startHighlight) + $('span', this).text().length; 
      start += diff; 
      end += diff; 
     } 

     // Remove the span 
     var spanText = $('span', this).contents().filter(textNodeFilter); 
     $(spanText).unwrap(); 
    } 

    var newText = haystack.substring(start, end).replace(needle, startHighlight + needle + endHighlight); 
    haystack = haystack.substring(0, start) + newText + haystack.substring(end); 

    $(this).html(haystack); 
}); 
+0

要知道,谷歌瀏覽器的選擇對象不公開'anchorOffset'等看起來是很難寫的這一個跨瀏覽器解決方案。 – Tomalak 2011-06-13 13:53:52