Copying styled text from a page to the clipboard with Javascript

混江龙づ霸主 提交于 2019-12-10 11:47:56

问题


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".


回答1:


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;
}


来源:https://stackoverflow.com/questions/5084713/copying-styled-text-from-a-page-to-the-clipboard-with-javascript

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