2016-11-22 2 views
1

Click to Copy機能には多くのソリューションがありますが、最も人気のあるものはclipboard.jsのようですが、特定のクラスを持つ要素だけをコピーできるソリューションは見つかりませんでした。例えばクリックすると、特定のクラスのすべての要素がクリップボードにコピーされますか?

<div class="wrapper"> 
    <div class="copytext">I want to copy this text</div> 
    <div class="nocopytext">I don't want to copy this text</div> 
    <div class="copytext">I also want to copy this text<div> 
</div> 
<button>Copy only classes with copytext</button> 

がどのように私は「copytext」すべてのクラスを選択するために、私のスクリプトを作成して、私のクリップボードにコピーしますが、何か他のものを除外することができますか?

+0

これはなんとかあるかどうか全く分かりません。回避策:1.すべてのnocopytext要素を非表示にする2.クリップボードを使用してコピー/カットする3.再度要素を表示する –

+0

[JavaScriptでクリップボードにコピーする方法は?](http:// stackoverflow .com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – pistou

+0

@pistouは本当にありません。 OPは間違いなくここで少し具体的な何かについて質問している。 –

答えて

3

利用document.getElementsByClasName()

<div class="wrapper"> 
    <div class="copytext">I want to copy this text</div> 
    <div class="nocopytext">I don't want to copy this text</div> 
    <div class="copytext">I also want to copy this text<div> 
</div> 
<button onclick="copyText()">Copy only classes with copytext</button> 
<div id="output"></div> 
<script> 
function copyText(){ 
    var outputText = ""; 
    var targets = document.getElementsByClassName('copytext'); 
    for(var i = 0; i < targets.length; i++) { 
    outputText += targets[i].innerText; 
    } 
    var output = document.getElementById('output'); 
    output.innerText = outputText; 
    var range = document.createRange(); 
    range.selectNodeContents(output); 
    var selection = window.getSelection(); 
    selection.removeAllRanges(); 
    selection.addRange(range); 
    document.execCommand('copy'); 
    output.style.display = 'none'; 
} 
</script> 
+0

賢明な出力ボックスの使用、ありがとう!それは素晴らしい作品です。 1つは、クリックしたときにテキストが強調表示されていることを示すためです。ドラッグしてドラッグしているように、あなた自身でコピーしますか? – cgrouge

+0

実際、元のラッパーを隠して出力ボックスを表示できますか?私はそれをスクリプトの最下部に追加しようとしましたが、https://jsfiddle.net/x5s8bhdx/のように動作させることができませんでした。関数の最後に – cgrouge

+0

を入れて、setTimeout(function(){output.innerText = ''; output.style.display = 'ブロック';}、100);また、スタイルプロパティをラッパー表示に追加します。 –

関連する問題