Chrome doesn't get the selected html string wr

2020-07-23 04:07发布

问题:

I'm using this solution by Tim Down to get selected html in a contenteditable div, and it's working fine (thank you Tim!) But using Chrome, if I select a html string exactly at the boundaries of a html tag, as in this image: http://i.imgur.com/UiYzrcp.png?1:

what I get it's just plain text (test in this case).

If I expand the selection to a next character (letter c for example), instead I get the correct html (<strong>test</strong> c).

Can I get the full html in Webkit by selecting a word like in the image? Thanks

回答1:

Not really. WebKit normalizes each boundary of any range when it's added to the selection so that it conforms to WebKit's idea of valid selection/caret positions in the document. You could change the original function so that it detects the case of a selection containing all the text within an element and expanding the selection range to surround that element (without actually changing the selection). Here's a simple example (you may need something cleverer for a more general case, such as when the text is inside nested elements, detecting block/inline elements, etc.):

Demo: http://jsfiddle.net/btLeg/

Code:

function adjustRange(range) {
    range = range.cloneRange();

    // Expand range to encompass complete element if element's text
    // is completely selected by the range
    var container = range.commonAncestorContainer;
    var parentElement = container.nodeType == 3 ?
            container.parentNode : container;

    if (parentElement.textContent == range.toString()) {
        range.selectNode(parentElement);
    }

    return range;
}

function getSelectionHtml() {
    var html = "", sel, range;
    if (typeof window.getSelection != "undefined") {
        sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                range = adjustRange( sel.getRangeAt(i) );
                container.appendChild(range.cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}