点击 复制文本到剪切板

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框架

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值