2017-04-25 58 views
1

我已經編寫了一個代碼,該代碼將根據下拉選擇在文本框中提供一些文本。 現在我想添加一個按鈕,將該文本框的內容複製到剪貼板。 我嘗試了很多東西,但他們都沒有工作。 我已經添加了按鈕,現在我需要一些關於如何編寫該功能的幫助,以便我可以通過單擊按鈕將文本框的內容複製到剪貼板中。如何使用Javascript中的複製按鈕將文本框的上下文複製到剪貼板中

<!DOCTYPE html> 
<html> 

<head> 

<link rel="stylesheet" type="text/css"> 

</head> 

<script> 

function myFunction() 
{ 
    var x = document.getElementById("Query").value; 

    if(x==""){ 
     document.getElementById("yourquery").value = " "; 
    } 

    if(x=="One"){ 
     document.getElementById("yourquery").value = "You have choosen number :1"; 
    } 

    if(x=="Two"){ 
     document.getElementById("yourquery").value = "You have choosen number :2"; 
    } 

    if(x=="Three"){ 
     document.getElementById("yourquery").value = "You have choosen number : 3" 
    } 

    if(x=="Four"){ 
     document.getElementById("yourquery").value = "You have choosen number :4"; 
    } 
} 


</script> 

<body> 
<form> 

<select id="Query" onchange="myFunction()"> 
     <option value=''>--Select Query--</option> 
     <option value='One'>One</option> 
     <option value='Two'>Two</option> 
     <option value='Three'>Three</option> 
     <option value='Four'>Four</option> 
</select> 

<fieldset style="max-width:600px";"max-width:600px"> 
<P>Your required query is: <input type="text" id="yourquery" size="50" style="width: 500px; height: 300px"></p> 

<input type="button" id="btnSearch" value="Copy To ClipBoard" onclick="GetValue();" /> 

</fieldset> 
</form> 

</body> 

</html> 

回答

0

複製到剪貼板是簡單的JS使用如下方法,並根據自己的需要修改:

var copyBTN = document.querySelector('.copy'); 
 

 
copyBTN.addEventListener('click', function(event) { 
 
    var textArea = document.querySelector('.text'); 
 
    textArea.select(); 
 
    try 
 
    { 
 
    var successful = document.execCommand('copy'); 
 
    var result = successful ? 'successful' : 'unsuccessful'; 
 
    alert('Copying was ' + result); 
 
    } catch (err) { 
 
    alert('unable to copy'); 
 
    } 
 
});
<p> 
 
    <textarea class="text">Hello I'm some text</textarea> 
 
</p> 
 

 
<p> 
 
    <button class="copy">Copy</button> 
 
</p>

UPDATE

如果你喜歡你可以使用第三方庫,如https://clipboardjs.com/

相關問題