【H5】使用h5實現復制粘貼功能


方案一 : 可滿足大部分瀏覽器正常使用

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>copy example</title>
</head>
<body>

<p>
  <button class="copy">Copy</button>
</p>
<p>
  <textarea cols="50" rows="10" placeholder="這這里粘貼試一下吧!"></textarea>
</p>

<script>

  var copyBtn = document.querySelector('.copy')

  // 點擊的時候調用 copyTextToClipboard() 方法就好了.
  copyBtn.onclick = function() {
    copyTextToClipboard('隨便復制點內容試試')
  }

  function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea")

    textArea.style.position = 'fixed'
    textArea.style.top = 0
    textArea.style.left = 0
    textArea.style.width = '2em'
    textArea.style.height = '2em'
    textArea.style.padding = 0
    textArea.style.border = 'none'
    textArea.style.outline = 'none'
    textArea.style.boxShadow = 'none'
    textArea.style.background = 'transparent'
    textArea.value = text

    document.body.appendChild(textArea)

    textArea.select()

    try {
      var msg = document.execCommand('copy') ? '成功' : '失敗'
      alert('復制內容 ' + msg);
    } catch (err) {
      alert('不能使用這種方法復制內容');
    }

    document.body.removeChild(textArea)
}

</script>

  
</body>
</html>

 

方案二: 兼容蘋果 iphone js 復制功能 clipboard.js

 

  下載地址: https://github.com/zenorocha/clipboard.js

<script src="你的路徑clipboard.min.js"></script>

<textarea id="bar" cols="62" rows="5" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"> 代碼改變世界 </textarea>
<!-- Trigger -->
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#bar">
Cut to clipboard
</button>
<script>
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
alert("復制成功");
e.clearSelection();
});
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM