开发者

Access an selected image within a contenteditable field in an iframe

I have a problem to get src or id or whatever of an selected开发者_JAVA百科 image that is inside a contenteditable div-container within an iframe. Well, it is possible to get the selected text information with a getSelection()-call like this:

window.document.getElementById("monitor").contentWindow.document.getSelection();
// "monitor" = iframe id

But if I select an image instead of text, I just got an empty result. I searched hours and hours but didn't find any solution. Does someone knows a way how to solve this problem? (I'm using Firefox 4)


window.getSelection() (for which document.getSelection() is an alias in HTML5-compliant browsers) returns a Selection object, not a string (it only superficially appears to be a string because its toString() method returns the selected text). The most useful aspect for this is the ability to get one or more DOM Range objects representing the selection using getRangeAt().

Once you have a Range, getting all the DOM nodes it contains is a little tricky. You could use my Rangy library, which adds a getNodes() method to its implementation of Range:

var sel = rangy.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    var elements = range.getNodes([1]);
    for (var i = 0; i < elements.length; ++i) {
        alert("Selected element: " + elements[i].tagName);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜