H5和移动端会有点击icon复制文本到剪切板
document.execCommand() 语法
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument) 返回值是布尔值,表示是否支持。
aCommandName: 一个 DOMString 作为指定要执行的指令。(指令可以为 “copy”,“cut” 等);
aShowDefaultUI: 一个 Boolean 作为指示是否展示用户界面,一般为 false;
aValueArgument: 针对需要提供输入引数的指令,借由 DOMString 提供相关的资讯。比如, insertImage 需要提供图片的 URL 。若沒有引数的需求則可指定为 null ;
HTML
<div>
{{ msg}}
<button @click="copy(msg)"><span class="iconcopy" style="margin-left: 10px" /></button>
</div>
由于 document.execCommand() 只能操作可编辑区域,即 input textarea 这样就要动态添加可编辑区域再删除。如果是 input 直接选取就行了
JS
export default {
methods: {
copy(msg) {
const input = document.createElement("input");
document.body.appendChild(input);
input.setAttribute("value", msg);
input.select();
if (document.execCommand("copy")) {
document.execCommand("copy");
console.log('复制成功!')
}
document.body.removeChild(input);
},
}
}
本篇用的是vue框架