JavaScript copy content to clipboard

        There are two situations for copying content to the clipboard. One is to select the content from the existing optional elements on the page to copy, and the other is to directly copy the string in the Javascript code to the clipboard.

Copy page element selection

        html code:

  <input type="textarea" id="txt" />
  <button onclick="copy()">复制</button>

        Javascript code:

        function copy() {
            var element = document.getElementById("txt");
            element.select();
            element.setSelectionRange(0, element.value.length);
            document.execCommand('copy');
            alert("已复制到剪切板");
        }

copy string to clipboard

        To copy a character string, add an element temporarily and copy it by simulating the selection of the selected content. After copying, remove the temporarily added element.

        Javascript code:

        //复制文本
        function copyText(text) {
            var element = createElement(text);
            element.select();
            element.setSelectionRange(0, element.value.length);
            document.execCommand('copy');
            element.remove();
            alert("已复制到剪切板");
        }

        //创建临时的输入框元素
        function createElement(text) {
            var isRTL = document.documentElement.getAttribute('dir') === 'rtl';
            var element = document.createElement('textarea');
            // 防止在ios中产生缩放效果
            element.style.fontSize = '12pt';
            // 重置盒模型
            element.style.border = '0';
            element.style.padding = '0';
            element.style.margin = '0';
            // 将元素移到屏幕外
            element.style.position = 'absolute';
            element.style[isRTL ? 'right' : 'left'] = '-9999px';
            // 移动元素到页面底部
            let yPosition = window.pageYOffset || document.documentElement.scrollTop;
            element.style.top = `${yPosition}px`;
            //设置元素只读
            element.setAttribute('readonly', '');
            element.value = text;
            document.body.appendChild(element);
            return element;
        }

        Demo code download: Native JavaScript copy content to the clipboard code example, no third-party library reference-Javascript Document Class Resources-CSDN Download

Guess you like

Origin blog.csdn.net/evanyanglibo/article/details/127851585