简体   繁体   中英

Copying styled text from a page to the clipboard with Javascript

I've created a simple tool so employees can personalize their company email signature. This tool creates some styled text with some bolded fonts and a bit of color, nothing fancy. If I then select the text and copy and paste it into my Gmail signature field all works well. It retains the formatting. However, I'd prefer to give the user the option of clicking a "Copy" button that copies the formatted content onto their clipboard.

I'm currently using ZeroClipboard to add the "copy to clipboard" functionality and it's working great. Thing is I don't know how to grab that formatted text. It just keeps copying the unformatted version. One thing I tried was adding a mouseDown listener to ZeroClipboard that selects the text like this:

function selectText() {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById('clicktocopy'));
        range.select();
    }
    else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById('clicktocopy'));
        window.getSelection().addRange(range);
    }
}

Then returns the selection like this:

function getText() {
    if (window.getSelection) {
        var range = window.getSelection();
        return range.toString();
    }
    else {
        if (document.selection.createRange) {
            var range = document.selection.createRange();
            return range.text;
        }
    }
}

However, this is only copying the unformatted text. Is it possible to copy the text formatted?

My formatted text is in a div with the id "results".

If you want an HTML string representing the current selection, the following function will do this (replacing your getText() function):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM