电商商城定制开发前端复制到剪贴板
-
电商商城定制开发有时候我们点击按钮,要将一些内容复制到剪贴板,大家是怎么实现的呢?
-
针对3种情况 , 实现点击按钮实现复制到剪贴板 👇
Ⅰ、点击,复制一个 input 框
- 表单元素是可以直接被选中的,我们直接 select 选中
<body> <input type="text" value="123456" id="textInput"> <button onclick="copyInput()">copy</button></body><script>function copyInput() { const input = document.getElementById("textInput"); input.select(); //选中该输入框 document.execCommand('copy'); //复制该文本 }</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 👉 选中该元素
- 👉 复制选中的内容
Ⅱ、点击,复制一个值
- 则需要个载体 ,我们先创建它,复制完成在删除
<body> <button onclick="copy(123456)">Copy</button></body><script>function copy(val) { const input = document.createElement("input"); //创建input input.setAttribute("value", val); //把input设置value document.body.appendChild(input); //添加这个dom对象 input.select(); //选中该输入框 document.execCommand("copy"); //复制该文本 document.body.removeChild(input); //移除输入框}</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 单纯复制一个值,实际上还是得选中一个元素
- 👉 创建 input
- 👉 设置其值
- 👉 在dom 中添加该元素
- 👉 选中该元素
- 👉 复制选中的内容
- 👉 移除 input
Ⅲ、点击,复制一个 dom 中的内容
非表单元素, 我们没办法选中,所以需要其他方法
<body> <div id="box">123456</div> <button onclick="copyDiv()"></button></body><script> function copyDiv() { var range = document.createRange(); range.selectNode(document.getElementById('box')); var selection = window.getSelection(); if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); return document.execCommand('copy'); }</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 👉 通过 createRange 返回 range 对象
- 👉 通过 range 的 selectNode 方法 选中 该 dom 的边界
- 👉 创建 selection 通过 addRange 去添加范围
- 👉 如果之前有则清空,然后添加这个range范围
- 👉 复制这个选中的范围