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「。
如何突出顯示選定的一個?
在此先感謝您的幫助。
要知道,谷歌瀏覽器的選擇對象不公開'anchorOffset'等看起來是很難寫的這一個跨瀏覽器解決方案。 – Tomalak 2011-06-13 13:53:52