页面上有任何选择可以自动复制到剪贴板

时间:2018-03-14 09:52:34

标签: javascript html dom

我需要将任何选项从网页复制到剪贴板,它可以是div,文本输入,密码输入,跨度等。

我有以下功能为我做这个,但挑战是要在剪贴板上设置函数的返回值

const getSelectionText = () => {
  let text = "";
  let activeDomElement = document.activeElement;
  let activeDomElementTagName = activeDomElement ? activeDomElement.tagName.toLowerCase() : null;

 if (
   (activeDomElementTagName === 'textarea') || (activeDomElementTagName ===  'input' &&
  /^(?:text|search|password|tel|url)$/i.test(activeDomElement.type)) &&
(typeof activeDomElement.selectionStart === "number")
 ) {   
     text = activeDomElement.value.slice(activeDomElement.selectionStart,   activeDomElement.selectionEnd);
   } else if (window.getSelection) {
     text = window.getSelection().toString();
  } 

return text;
}

任何想法或资源链接都会有所帮助,谢谢

2 个答案:

答案 0 :(得分:1)

看看w3schools的例子。这是一个基本的例子。

https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

你也可以用这个 - 只需使用返回的文本作为参数调用myFunction。

function myFunction(arg) {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value",arg);
    x.select();
    document.execCommand("Copy");
    alert("Copied the text: " + x.value);
    document.removeChild(x);
}

答案 1 :(得分:0)

document.execCommand("copy")这将复制您选择的所有文字!

       function copySelectionText(){
        var copysuccess // var to check whether execCommand successfully executed
        try{
            copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
        } catch(e){
            copysuccess = false
        }
        return copysuccess
    }
    document.body.addEventListener('mouseup', function(e){
        var copysuccess = copySelectionText() // copy user selected text to clipboard
        if(copysuccess) {
           document.getElementById('paste').style.display = "block";
        }
    }, false)
     <h3>Late</h3>
    <p>dsfjdslkfjdslkfjdsklfj</p>
    <code>Cdoing is godo for a wite </code>


    <textarea placeholder="Paste Here with [Ctrl + V ]" style="display:none;" id="paste"> </textarea>