2016-11-22 29 views
1

我知道有很多點擊複製功能的解決方案,其中一個最流行的似乎是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.使用clipboard.js複製/剪切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

巧妙使用輸出盒,謝謝!它效果很好。有一件事,無論如何顯示點擊時突出顯示的文本?就好像你是點擊拖動來自己複製它? – cgrouge

+0

其實,我可以隱藏原始包裝並顯示輸出框嗎?我嘗試將其添加到腳本的底部,並且無法使其工作https://jsfiddle.net/x5s8bhdx/ – cgrouge

+0

在函數的末尾放置了類似setTimeout(function(){output.innerText = ''; output.style.display ='block';},100);還要將樣式屬性添加到包裝顯示中:無; –