问题
I created a contentEditable div with a text portion and a link. Double clicking the link will select the link text.
<div contentEditable="true">
This is a text and <a href="http://www.google.com">This_is_a_link</a>
</div>
Afterwards calling document.getSelection().getRangeAt(0).startContainer will return the div:
// => <div contenteditable="true">
Instead of the link. I cannot find a way to find which part of the div is selected.
See this jsfiddle (double click the "This_is_a_link" and there will be a console log with startContainer): http://jsfiddle.net/UExsS/1/
(Obligatory JS code from the fiddle)
$(function(){
$('a').dblclick(function(e) {
setTimeout(function() {
console.log(window.getSelection().getRangeAt(0));
}, 500);
});
});
Note, that Chrome has the correct behavior, and running the above jsfiddle in Chrome will give textElement for startContainer.
Has anyone run into this issue? did you find a workaround?
回答1:
Don't think its a bug of Firefox, just a different kind of implementation. When you double click the link, Firefox selects not only the text, but the whole a-tag, so the parent node of the selection is correctly set to the div container.
I added these few lines of code to your fiddle to proof that point:
var linknode = window.getSelection().getRangeAt(0).commonAncestorContainer.childNodes[1];
console.log(linknode);
console.log(window.getSelection().containsNode(linknode, false));
Forked fiddle: http://jsfiddle.net/XZ6vc/
When you run it, you'll see in the javascript console that linknode contains your link, and the check if the link is fully contained in the selection returns true.
This is also one possible solution to the problem, albeit not ideal one. Iterate over all the links in your contenteditable and check if one of them is fully contained in the selection.
Though one word of advice: Don't reinvent the wheel if you don't have to ;-) There's quite possibly some libraries / frameworks out there that fit your needs.
来源:https://stackoverflow.com/questions/19234988/firefox-how-to-get-selected-text-when-using-double-click