window.getSelection()
返回一个包含 start ( ) 和 end ( )的selection
对象 ( ref )。因此,根据您提供的 HTML - 将 ID 修改为不只使用数字 ( ref ) - 这是一个演示。单击任何单词,或选择一组单词以查看它们获得“红色”类名称。anchorNode
extentNode
修改后的 HTML
<div>
<p><span id="s1">word1</span> <span id="s2">word2</span> </p>
<div><span id="s3">word3</span> <span id="s4">word4</span></div>
<ul>
<li><span id="s5">word5</span> <span id="s6">word6</span></li>
</ul>
<p><span id="s7">word7</span> <span id="s8">word8</span> <strong><span id="s9">word9</span></strong> </p>
</div>
脚本
$('div').bind('mouseup', function(){
var i,
s = window.getSelection(),
// get ID of starting node
start = parseInt((s.anchorNode.parentNode.id || '').substring(1), 10),
// get ID of end node
end = parseInt((s.extentNode.parentNode.id || '').substring(1), 10),
// start gathering spans
spans = $('#s' + start);
// remove selected class
$('span[id^=s]').removeClass('red');
// add each span
for (i = start; i <= end; i++) {
spans = spans.add( $('#s' + i) );
}
// add selected class
spans.addClass('red');
});
</p>