在前端开发需求中,为了方便用户使用,经常需要通过点击按钮复制指定的某一段内容。
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 |
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title></head><body> <input type="text" id="testInput" value="testInput"> <div id="testDiv">testdiv</div> <button id="copyTestInput">复制输入框内容</button> <button id="copyTestDiv">复制div文本内容</button> <script> /* * 复制输入框内容 */ function copyInput() { var copyVal = document.querySelector("#testInput"); copyVal.select(); return document.execCommand('copy'); } /* * 复制元素节点的内容 */ function copyDiv() { var range = document.createRange(); range.selectNode(document.querySelector('#testDiv')); var selection = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); return document.execCommand('copy'); } /* * 提示 * param {Boolean} status */ function tips(status) { if (status) { alert('复制内容成功'); } else { alert('复制失败,可选中内容手动复制'); } } document.querySelector('#copyTestInput').addEventListener('click', function() { var isCopyed = copyInput(); tips(isCopyed); }, false); document.querySelector('#copyTestDiv').addEventListener('click', function() { var isCopyed = copyDiv(); tips(isCopyed); }, false); </script></body></html>测试地址:https://jsbin.com/qobutuhidu/1/edit?html,js,output
input输入类型的元素
普通类型元素