当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 点击复制到剪切板

点击复制到剪切板

2019年03月24日  | 移动技术网IT编程  | 我要评论

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

<!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="width: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>

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网