Firefox - how to get selected text when using double click

荒凉一梦 提交于 2019-12-23 20:47:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!