Get span Id's of selected text using getSelected()
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a spa开发者_如何学Pythonn with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.
So a simple example of a paragraph is below.
<span id="p-58" class="softWord" onClick="setTranscriptPosition(-58);return false"> that </span>
<span id="p177" class="softWord" onClick="setTranscriptPosition(177);return false"> quake </span>
<span id="p857" class="softWord" onClick="setTranscriptPosition(857);return false"> briefly </span>
<span id="p1697" class="softWord" onClick="setTranscriptPosition(1697);return false"> triggering </span>
<span id="p2267" class="softWord" onClick="setTranscriptPosition(2267);return false"> another </span>
<span id="p2697" class="softWord" onClick="setTranscriptPosition(2697);return false"> tsunami </span>
I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
How would i get the id's of those spans though?
Ok, this will do exactly what you need. It's thanks to my friend's work on a project we did together, so the credit belongs to him:
http://jsfiddle.net/KC48j/11/
Just select some text and hit the button. EDIT: updated to work with IE as well. You can mess around with the logic yourself (how it handles whitespace between words is up to you).
If you don't mind using a library, my Rangy library makes this pretty simple. The following will work in all major browsers (including IE 6):
jsFiddle: http://jsfiddle.net/VC3hk/24/
Code:
function getSelectedSpanIds() {
var sel = rangy.getSelection(), ids = [];
for (var r = 0, range, spans; r < sel.rangeCount; ++r) {
range = sel.getRangeAt(r);
if (range.startContainer == range.endContainer && range.startContainer.nodeType == 3) {
range = range.cloneRange();
range.selectNode(range.startContainer.parentNode);
}
spans = range.getNodes([1], function(node) {
return node.nodeName.toLowerCase() == "span";
});
for (var i = 0, len = spans.length; i < len; ++i) {
ids.push(spans[i].id);
}
}
return ids;
}
document.onkeyup = document.onmouseup = function() {
alert(getSelectedSpanIds());
};
I think that your over complicating it, just use mouseup()
jquery
$('span').mouseup(function(){
alert($(this).attr('id'));
});
Check it out here - http://jsfiddle.net/ajthomascouk/Qdv4T/
精彩评论