Skip to content

Instantly share code, notes, and snippets.

@yoshiki-0428
Last active June 20, 2020 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshiki-0428/c8d014f49ecb4962e1fe191fea2c32b7 to your computer and use it in GitHub Desktop.
Save yoshiki-0428/c8d014f49ecb4962e1fe191fea2c32b7 to your computer and use it in GitHub Desktop.
function execCopy(string){
// 空div 生成
var tmp = document.createElement("div");
// 選択用のタグ生成
var pre = document.createElement('pre');
// 親要素のCSSで user-select: none だとコピーできないので書き換える
pre.style.webkitUserSelect = 'auto';
pre.style.userSelect = 'auto';
tmp.appendChild(pre).textContent = string;
// 要素を画面外へ
var s = tmp.style;
s.position = 'fixed';
s.right = '200%';
// body に追加
document.body.appendChild(tmp);
// 要素を選択
document.getSelection().selectAllChildren(tmp);
// クリップボードにコピー
var result = document.execCommand("copy");
// 要素削除
document.body.removeChild(tmp);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment