javascript复制元素到所有样式的剪贴板

时间:2018-02-01 01:31:57

标签: javascript html clipboard

我正在尝试将div复制到剪贴板。 div有一些样式,包括背景。我已经制作了一个脚本来将div复制到剪贴板,但我无法弄清楚如何做背景。

我已经看到了这一点,但我不记得是怎么做的。

任何帮助都将不胜感激。

据我所知:

function executeCopy(text) {
    var copyDiv = document.createElement('div');
    copyDiv.contentEditable = true;
    document.body.appendChild(copyDiv);
    copyDiv.innerHTML = text;
    copyDiv.unselectable = "off";
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    document.body.removeChild(copyDiv);
}
#foo {
  background-color: red;
  font-family: cursive;
}
<div id="foo">Test</div>
<button onclick="executeCopy(document.getElementById('foo').innerHTML);">Copy</button>

1 个答案:

答案 0 :(得分:1)

您可以尝试以下小提琴。它适用于所有文本样式,并且可以与MS Word和Pages进行互操作(我刚刚测试过它)。

代码很简单,所以我不会真正深入到它的深处,但如果您愿意,可以随意给我任何问题。 :)

import json
import requests

# testing user password database:
testingUsers = {
    'testingUser2@funnymail.com': 'BuQ3tUS3 :jbFAL',
    'testingUser3w@funnymail.com': 'y(1726854(b(-KY'
    }


def getUserToken(userName):
    # client id and secret come from LogIn (Test Client)! which has password enabled under "Client > Advanced > Grant Types > Tick Password"
    url = 'https://YOUR_AUTH0_DOMAIN/oauth/token' 
    headers = {'content-type': 'application/json'}
    password = testingUsers[userName]
    parameter = { "client_id":"Jfjrl12w55uqcJswWmMhSm5IG2Qov8w2e", 
                  "client_secret": "3E5ZnqLFbPUppBLQiGDjB0H2GtXaLyaD26sdk2HmHrBXQaDYE453UCUoUHmt5nWWh",
                  "audience": 'AUTH0_AUDIENCE',
                  "grant_type": "password",
                  "username": userName,
                  "password": password, "scope": "openid" } 
    # do the equivalent of a CURL request from https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing
    responseDICT = json.loads(requests.post(url, json=parameter, headers=headers).text)
    return responseDICT['access_token']

@memoize # memoize code from: https://stackoverflow.com/a/815160
def getUserTokenHeaders(userName='testingUser2@funnymail.com'):
    return { 'authorization': "Bearer " + getUserToken(userName)} 

https://jsfiddle.net/aypdg3kL/