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、貼り付けられるはずです。
ベストアンサー1
2020年更新:このソリューションでは を使用します
execCommand
。この回答を書いている時点ではその機能は問題ありませんでしたが、今では時代遅れとみなされている多くのブラウザで引き続き動作しますが、サポートが中止される可能性があるため、使用は推奨されません。
Flashを使わない別の方法もあります(クリップボード API言及されているjfriend00の回答)。テキストを選択してからコマンドを実行するcopy
ページ上で現在選択されているテキストをクリップボードにコピーします。
たとえば、この関数は渡された要素の内容をクリップボードにコピーします(コメントの提案で更新されました)ポイントゼロツー):
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
仕組みは以下のとおりです:
- 一時的に非表示のテキスト フィールドを作成します。
- 要素の内容をそのテキスト フィールドにコピーします。
- テキスト フィールドの内容を選択します。
- 次のようにコマンド copy を実行します
document.execCommand("copy")
。 - 一時的なテキスト フィールドを削除します。
要素の内部テキストには空白を含めることができることに注意してください$(element).text().trim()
。したがって、たとえばパスワードに使用したい場合は、上記のコードで を使用してテキストをトリミングできます。
簡単なデモはここでご覧いただけます:
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" />
主な問題は、すべてのブラウザのサポート現時点ではこの機能はサポートされていませんが、次の主要な機能で使用できます。
- クローム43
- インターネットエクスプローラー10
- ファイアフォックス41
- サファリ10
更新 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 を渡すことに注意してください。
としてマドゾハン以下のコメントで報告されているように、Google Chrome の 64 ビット バージョンでは、場合によっては奇妙な問題が発生します (ファイルをローカルで実行)。この問題は、上記の jQuery 以外のソリューションで修正されるようです。
Madzohan は Safari で試しましたが、解決策は機能しましたが、document.execCommand('SelectAll')
ではなく を使用しました.select()
(チャットと以下のコメントで指定されているとおり)。
としてPointZeroTwoはコメントで指摘している成功/失敗の結果を返すようにコードを改善できます。デモはこのjsFiddle。
更新: テキスト形式を維持したコピー
としてStackOverflowのスペイン語版でユーザーが指摘した、上記の解決策は、要素の内容を文字通りコピーする場合は完璧に機能しますが、コピーしたテキストをフォーマット付きで貼り付ける場合はそれほどうまく機能しません ( にコピーされるとinput type="text"
、フォーマットは「失われます」)。
これを解決するには、コンテンツ編集可能領域にコピーし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>