js实现点击复制网页内容(基于execCommand)

通过execCommand方法来实现,当一个HTML文档切换到设计模式 designMode时,文档对象暴露 execCommand 方法,该方法允许运行命令来操纵可编辑区域的内容。大多数命令影响文档的选择(粗体,斜体等),而其他命令插入新元素(添加链接)或影响整行(缩进)。当使用contentEditable时,调用 execCommand() 将影响当前活动的可编辑元素。语法如下:

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument);
注:在项目开发过程中,PC端没有问题,兼容性不错,但是在移动端ios手机却无法实现复制,兼容性不行,android没问题。。。
具体实现方法如下代码:

html:

<span class="tip">点击可复制</span>
<div class="wrapper">            
<p id="text" onclick="copyText()">我把你当兄弟你却想着复制我?</p>
<textarea id="input">这是幕后黑手</textarea>        
</div>

CSS:

.wrapper {
    position: relative;
    background-color: #F1F1F1;
    width: 300px;
    height: 30px;
}
            
#input {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: -10;
}
.tip{
    display: inline-block;
    background-color: #333;
    width: 90px;
    color: #fff;
    height: 30px;
    text-align: center;
    line-height: 30px;
    border-radius: 4px;
    display: none;
    position: absolute;
    top: 50px;
    left: 0px;
    opacity: 0.8;
}

js:

document.getElementsByClassName('wrapper')[0].onmouseenter=function(){
   document.getElementsByClassName('tip')[0].style.display='block';             
};
document.getElementsByClassName('wrapper')[0].onmouseleave=function(){
    document.getElementsByClassName('tip')[0].style.display='none';
 };
 function copyText() {
       var text = document.getElementById("text").innerText;
       var input = document.getElementById("input");
       input.value = text; // 修改文本框的内容
       input.select(); // 选中文本
       document.execCommand("copy"); // 执行浏览器复制命令
       alert("复制成功");
}

 参考链接:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

原文地址:https://www.cnblogs.com/web-wjg/p/8616336.html