前端实现复制功能

前情
在前端开发需求中,为了方便用户使用,经常需要通过点击按钮复制指定的某一段内容。
相关API
Document.createRange()
返回一个Renge对象,通过Range对象可以选中文本。

// 选中id为test的元素的内容 const range = document.createRange(); range.selectNode(document.getElementById('test')); const selection = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range);

Window.getSelection
返回一个 Selection对象,表示用户选择的文本范围或光标的当前位置。
const selection = window.getSelection(); const selectedText = selection.toString(); // 获取当前选中的文本 console.log(selectedText)

document.execCommand
【前端实现复制功能】document暴露 execCommand方法,该方法允许运行命令来操纵可编辑内容区域的元素
// const bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument); const bool = document.execCommand('copy'); // 执行复制命令

参数说明
aCommandName 一个 String,命令的名称,如copy
aShowDefaultUI 一个 Boolean, 是否展示用户界面,一般为 false。Mozilla 没有实现
aValueArgument 一些命令(例如insertImage)需要额外的参数(insertImage需要提供插入image的url),默认为null
使用示例
JS Bin testdiv

  • 如果是输入类型元素:直接调用select方法选中内容,再启动copy命令
  • 如果是普通元素 :需要通过document.createRange选中节点内容,再通过window.getSelection选中元素内容,再启动copy命令
测试地址:https://jsbin.com/qobutuhidu/1/edit?html,js,output
注意
input输入类型的元素
  • 不能有disabled属性
  • width || height 不能为0
  • 不能有hidden、display:none属性
普通类型元素
  • width || height 不能为0
  • 不能有display:none属性

    推荐阅读