2016-11-28 5 views
-2

とvairable JSからテキストをクリップボードにコピーすることができますどのように、私は変数私はJSでjQueryの

var text = "this is a test"; 

を持っていると私は私のHTMLのボタンをクリックしたとき、それは

function nameoffunction(){ 
} 
JSのfuncitonを呼び出します

関数が呼び出されたときに "これはテストです"というクリップボードにコピーしたいと思います。

どうすればいいですか?

+0

https://clipboardjs.com/ –

+0

clipboardjs.com答えました。 – user3011784

答えて

0

Javascriptを

<script> 
    function CopyToClipboard(text) { 
    var textArea = document.createElement("textarea"); 

    // Place in top-left corner of screen regardless of scroll position. 
    textArea.style.position = 'fixed'; 
    textArea.style.top = 0; 
    textArea.style.left = 0; 

    // Ensure it has a small width and height. Setting to 1px/1em 
    // doesn't work as this gives a negative w/h on some browsers. 
    textArea.style.width = '2em'; 
    textArea.style.height = '2em'; 

    // We don't need padding, reducing the size if it does flash render. 
    textArea.style.padding = 0; 

    // Clean up any borders. 
    textArea.style.border = 'none'; 
    textArea.style.outline = 'none'; 
    textArea.style.boxShadow = 'none'; 

    // Avoid flash of white box if rendered for any reason. 
    textArea.style.background = 'transparent'; 


    textArea.value = text; 

    document.body.appendChild(textArea); 

    textArea.select(); 

    try { 
    var successful = document.execCommand('copy'); 
    var msg = successful ? 'successful' : 'unsuccessful'; 
    console.log('Copying text command was ' + msg); 
    } catch (err) { 
    console.log('Oops, unable to copy'); 
    } 

    document.body.removeChild(textArea); 
} 


var copyBtn = document.querySelector('#CopyBtn'); 

copyBtn.addEventListener('click', function(event) { 
    var text = "this is a test"; 
    CopyToClipboard(text); 
}); 

</script> 

HTML

<p> 
<button id="CopyBtn">Copy to clipboard</button> 
</p> 

Ref

関連する問題