div内のテキストをクリップボードにコピーするには?私はdivを持っていて、テキストをクリップボードに追加するリンクを追加する必要があります。これに対する解決策はありますか?
<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
<a class="copy-text">copy Text</a>
テキストのコピーをクリックした後に、Ctrl+Vを押すと、ペーストされなければなりません。
もう一つFlash以外の方法があります(jfriend00's answerで紹介した[Clipboard API][1]以外に)。テキストを選択し、コマンド copy
を実行して、ページ上で現在選択されているテキストをクリップボードにコピーする必要があります。
例えば、この関数は、渡された要素の内容をクリップボードにコピーします(PointZeroTwoからのコメントで提案されて更新されました)。
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
このような仕組みになっています。
1.一時的な隠しテキストフィールドを作成します。 2.要素の内容をそのテキストフィールドにコピーします。 3.テキストフィールドの内容を選択する。 4.コピーというコマンドを実行します。document.execCommand("copy")`のように実行します。 5.一時的なテキストフィールドを削除します。
簡単なデモはこちらでご覧いただけます。
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
主な問題は、現時点ではすべての[ブラウザ]がこの機能をサポートしているわけではないことですが、以下の主要なブラウザでは使用することができます。
Update 1: これは、純粋なJavaScriptソリューション(jQueryを使用しない)でも実現できます。
function copyToClipboard(elementId) {
// Create a "hidden" input
var aux = document.createElement("input");
// Assign it the value of the specified element
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
// Append it to the body
document.body.appendChild(aux);
// Highlight its content
aux.select();
// Copy the highlighted text
document.execCommand("copy");
// Remove it from the body
document.body.removeChild(aux);
}
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />
現在は#を付けずにidを渡していることに注意してください。
madzohan]6が下のコメントで報告しているように、64ビット版のGoogle Chromeでは一部のケースで奇妙な問題が発生しています(ファイルをローカルで実行している場合)。この問題は、上記のjQueryを使わない方法で修正されたようです。
MadzohanはSafariで試してみましたが、解決策はうまくいきました。ただし、.select()
を使用する代わりに、document.execCommand('SelectAll')
を使用しています(チャットと下記コメントで指定されています)。
PointZeroTwoがコメントで指摘しているように]4、このコードは成功/失敗の結果を返すように改善することができます。デモは[このjsFiddle][7]で見ることができます。
StackOverflowのスペイン語版でユーザーが指摘したように]8、上記の解決策は、要素の内容をそのままコピーする場合には完璧に機能しますが、コピーしたテキストを書式付きで貼り付けたい場合にはそれほどうまく機能しません(input type="text"
にコピーされるため、書式は"lost"となります)。
これを解決するには、コンテンツの編集可能な div
にコピーして、同様に execCommand
を使ってコピーすることになります。ここに例があります。コピーボタンをクリックしてから、下のコンテンツ編集可能なボックスにペーストしてください。
function copy(element_id){
var aux = document.createElement("div");
aux.setAttribute("contentEditable", true);
aux.innerHTML = document.getElementById(element_id).innerHTML;
aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
document.body.appendChild(aux);
aux.focus();
document.execCommand("copy");
document.body.removeChild(aux);
}
#target {
width:400px;
height:100px;
border:1px solid #ccc;
}
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button>
<div id="target" contentEditable="true"></div>
で、jQueryだとこんな感じになります。
function copy(selector){
var $temp = $("<div>");
$("body").append($temp);
$temp.attr("contenteditable", true)
.html($(selector).html()).select()
.on("focus", function() { document.execCommand('selectAll',false,null); })
.focus();
document.execCommand("copy");
$temp.remove();
}
#target {
width:400px;
height:100px;
border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button>
<div id="target" contentEditable="true"></div>
**2016年時点での編集内容です。
2016年現在、ほとんどのブラウザでテキストをクリップボードにコピーできるようになりました。これは、ほとんどのブラウザが、選択範囲を離れて動作するdocument.execCommand("copy")
を使って、プログラムでテキストの選択範囲をクリップボードにコピーする機能を持っているからです。
ブラウザの他のアクション(新しいウィンドウを開くなど)と同様に、クリップボードへのコピーは特定のユーザーアクション(マウスクリックなど)を介してのみ行うことができます。 例えば、タイマーを使ってコピーすることはできません。
以下にコード例を示します。
document.getElementById("copyButton").addEventListener("click", function() {
copyToClipboard(document.getElementById("copyTarget"));
});
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
input {
width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">
もう少し進んだデモをご紹介します。
また、clipboard.jsでは、これを実現するビルド済みのライブラリを入手することができます。
答えの古い、歴史的な部分。
JavaScriptでクリップボードに直接コピーすることは、セキュリティ上の理由から、最近のブラウザでは許可されていません。最も一般的な回避策は、ユーザーが直接クリックした場合にのみ起動するクリップボードへのコピー用のFlash機能を使用することです。
すでに述べたように、ZeroClipboardは、コピーを行うFlashオブジェクトを管理するための人気のあるコードセットです。私も使ったことがあります。閲覧デバイスにFlashがインストールされていれば(モバイルやタブレットは除外されます)、動作します。
次によくある回避策は、クリップボードに入れたテキストを入力フィールドに配置し、そのフィールドにフォーカスを移して、Ctrl + C を押してテキストをコピーするようにユーザーに指示することです。
この問題に関する他の議論や回避策については、Stack Overflowの以下の先行記事をご覧ください。
https://stackoverflow.com/questions/1539641/how-to-copy-text-to-the-clients-clipboard-using-jquery
How can you copy to clipboard without Flash?
これらの質問は、Flashを使用しない現代的な代替手段を求めていますが、多くの質問が寄せられていますが、解決策を示す回答はありません(おそらく存在しないからでしょう)。
https://stackoverflow.com/questions/6355300/copy-to-clipboard-without-flash
Internet ExplorerやFirefoxでは、クリップボードにアクセスするための非標準的なAPIを備えていましたが、最新のバージョンでは(おそらくセキュリティ上の理由から)それらの方法は非推奨となっています。
最も一般的なクリップボードの問題を解決するための"safe"方法を考え出そうとするnascent standards effortがあり、FirefoxやChromeの最新バージョンでは部分的に実装されているようですが、まだ確認していません。
コピーするテキストはテキスト入力で、以下のようになります。 <input type="text" id="copyText" name="copyText">
そして、ボタンをクリックすると上のテキストがクリップボードにコピーされるようにしたいので、ボタンは以下のようにします。<button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button>
あなたのスクリプトは次のようになります。
<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
moviePath: "ZeroClipboard.swf"
});
});
</script>
CDNファイルの場合
note:ZeroClipboard.swf "と "ZeroClipboard.js "は、この機能を使用するファイルと同じフォルダにある必要があります。または、私たちがページに"<script src=""></script>`を含めるようにしなければなりません。