【问题标题】:Copy to clipboard option for IE9, IE11 and Safari复制到 IE9、IE11 和 Safari 的剪贴板选项
【发布时间】:2021-04-14 01:10:30
【问题描述】:

我正在尝试在网页上实现复制到剪贴板按钮。下面是我写的代码

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" /> 

但是,这似乎不适用于 IE 9、11Safari。是否有任何更改/替代实现我可以用来在我的网页上实现它。

【问题讨论】:

  • 答案将来自链接here

标签: javascript html internet-explorer safari cross-browser


【解决方案1】:

不确定 Safari,但在 IE 上可以:

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

我希望它有所帮助。干杯

【讨论】:

    【解决方案2】:

    你可以检查一下我用过它你可以通过按下按钮复制文本并将其粘贴到任何地方进行测试..

    $('#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");
                        setTimeout(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");
                        setTimeout(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>

    【讨论】:

    • 这个答案效果很好。但是,请将您的setInterval 更改为setTimeout,否则该功能将无限触发,并​​且您所做的每个文本选择都会再次被删除...
    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多