且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript-将所有HTML代码复制到剪贴板

更新时间:2023-11-02 23:45:22

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 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);
}
$(document).ready(function() {
  $("#btnDate").click(function() {
    var allHTML = document.documentElement.outerHTML;
    copyTextToClipboard(allHTML);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="btnDate" class="btn btn-primary">Copy HTML
</button>