Copy to clipboard option for IE9, IE11 and Safari

蹲街弑〆低调 提交于 2019-12-10 07:06:06

问题


I am trying to implement a copy-to-clipboard button on a webpage. Below is the code I have written

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">Text1</p>
   <p id="p2">Text2</p>
   <button onclick="copyToClipboard('#p1')">Copy Text1</button>
   <button onclick="copyToClipboard('#p2')">Copy Text2</button>
   <br/><br/>
   <input type="text" placeholder="Paste here for test" /> 

However, this does not seem to work on IE 9, 11 and Safari. Is there any change/alternate implementation I can use to implement this on my webpage.


回答1:


You can check this i used it you can copy text by pressing button and paste it any where to test..

$('#btnCopytext').click(function () {
                var element = document.getElementById('p1');
                if (document.body.createTextRange) { // ie
                    var range = document.body.createTextRange();
                    range.moveToElementText(element);
                    range.select();
                    document.execCommand("Copy");
                    setInterval(function () { selection.removeAllRanges(); }, 1000);
                   
                } else if (window.getSelection) { // moz, opera, webkit
                    var selection = window.getSelection();
                    var range = document.createRange();
                    range.selectNodeContents(element);
                    selection.removeAllRanges();
                    selection.addRange(range);
                    document.execCommand("Copy");
                    setInterval(function () { selection.removeAllRanges(); }, 1000);
                    

                }
            });
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<p id="p1">Text1</p>

<button id='btnCopytext'>Copy Text1</button>



</html>



回答2:


Not sure about Safari, but on IE you can do:

window.clipboardData.setData('Text', 'text you want to copy goes here');

I hope it helps. Cheers



来源:https://stackoverflow.com/questions/34434373/copy-to-clipboard-option-for-ie9-ie11-and-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!