Javascript - Copy string to clipboard as text/html

前端 未结 3 1988
慢半拍i
慢半拍i 2020-12-03 02:49

Is there a way in javascript to copy an html string (ie xx) into the clipboard as text/html, so that it can then be pasted into for example a

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 03:03

    There is a much simpler solution. Copy a section of your page (element) than copying HTML.

    With this simple function you can copy whatever you want (text, images, tables, etc.) on your page or the whole document to the clipboard. The function receives the element id or the element itself.

    function copyElementToClipboard(element) {
      window.getSelection().removeAllRanges();
      let range = document.createRange();
      range.selectNode(typeof element === 'string' ? document.getElementById(element) : element);
      window.getSelection().addRange(range);
      document.execCommand('copy');
      window.getSelection().removeAllRanges();
    }
    

    How to use:

    copyElementToClipboard(document.body);
    copyElementToClipboard('myImageId');
    

提交回复
热议问题