欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

web将内容拷贝到剪切板

程序员文章站 2022-03-04 14:24:33
...
var webCopyString = function(str){
                console.log('复制');
            
                var input = str + '';
                const el = document.createElement('textarea');
                el.value = input;
                el.setAttribute('readonly', '');
                el.style.contain = 'strict';
                el.style.position = 'absolute';
                el.style.left = '-9999px';
                el.style.fontSize = '12pt'; // Prevent zooming on iOS
            
                const selection = getSelection();
                var originalRange = false;
                if (selection.rangeCount > 0) {
                    originalRange = selection.getRangeAt(0);
                }
                document.body.appendChild(el);
                el.select();
                el.selectionStart = 0;
                el.selectionEnd = input.length;
            
                var success = false;
                try {
                    success = document.execCommand('copy');
                } catch (err) {}
            
                document.body.removeChild(el);
            
                if (originalRange) {
                    selection.removeAllRanges();
                    selection.addRange(originalRange);
                }
            
                return success;
            }