点击复制到剪切板

点击复制到剪切板,兼容性很好,可以自定义样式,加以美化。

<!DOCTYPE html>    
<html lang="en">    
<head>    
    <meta charset="UTF-8">          
    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>点击复制到剪切板</title>
</head>    
<body>    

<h2>点击粘贴出现《我被复制了》</h2>

<button id="clip_button" onClick="copyNum()">点击复制到剪切板</button><br/><br/>

<!-- 测试是否复制 -->
<textarea></textarea>

<!-- 将复制内容隐藏 -->
<input type="text" id="clip_num" style="1px;height:1px;position:absolute;top:-10px;left:-10px" value="我被复制了">


<script>
    // 思路:要想复制到剪贴板,必须先选中这段文字。
    function copyNum(){
        var NumClip=document.getElementById("clip_num");
        var NValue=NumClip.value;
        var valueLength = NValue.length;
        selectText(NumClip, 0, valueLength);
        if(document.execCommand('copy', false, null)){
            document.execCommand('copy', false, null)// 执行浏览器复制命令
            console.log("已复制,赶紧分享给朋友吧");
        }else{
            console.log("不兼容");
        }
    }
    // input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
    // 选择文本。createTextRange(setSelectionRange)是input方法
    function selectText(textbox, startIndex, stopIndex) {
        if(textbox.createTextRange) {//ie
            var range = textbox.createTextRange();
            range.collapse(true);
            range.moveStart('character', startIndex);//起始光标
            range.moveEnd('character', stopIndex - startIndex);//结束光标
            range.select();//不兼容苹果
        }else{//firefox/chrome
            textbox.setSelectionRange(startIndex, stopIndex);
            textbox.focus();
        }
    }
/*兼容性补充:
    移动端:
    安卓手机:微信(chrome)和几个手机浏览器都可以用。 
    苹果手机:微信里面和sarafi浏览器里也都可以,  
  PC端:sarafi版本必须在10.2以上,其他浏览器可以.
    兼容性测试网站:https://www.caniuse.com/
 */
</script>
</body> 
</html>
原文地址:https://www.cnblogs.com/wrongcode/p/10584373.html