700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > js 复制指定元素内的文本信息到剪切板(navigator.clipboard和document.execCommand)

js 复制指定元素内的文本信息到剪切板(navigator.clipboard和document.execCommand)

时间:2018-08-15 10:41:44

相关推荐

js 复制指定元素内的文本信息到剪切板(navigator.clipboard和document.execCommand)

因为 document.execCommand(‘copy’)已被弃用,所以我们首选navigator.clipboard进行异步获取

//navigator clipboard 向剪贴板写文本navigator.clipboard.writeText(内容).then(function() {alert("复制成功")}, function() {alert("复制失败")});

但是某些浏览器禁用了非安全域的 navigator.clipboard 对象,这时候navigator.clipboard不可用,就需要我们使用已弃用的document.execCommand(‘copy’)

var rangeif (document.body.createTextRange) {range = document.body.createTextRange();range.moveToElementText(div);range.select();} else if (window.getSelection) {var selection = window.getSelection();range = document.createRange();range.selectNodeContents(div); // 创建选取内容范围selection.removeAllRanges(); // 清除已选择的内容selection.addRange(range); // 添加选取内容,模拟用户选取/*if(selection.setBaseAndExtent){selection.setBaseAndExtent(text, 0, text, 1);}*/} else {console.warn("none");}document.execCommand('copy'); // 触发复制事件alert("复制成功")document.execCommand("unselect", "false", null) // 取消选取区域

完整的代码如下:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>复制指定元素内的文本信息</title></head><style>html, body {margin: 0;font-size: 14px;}button{margin-top: 20px;}p{font-size: 14px;color: #666;line-height: 20px;text-indent: 2em;}</style><body><button onclick="copyText()">复制文本</button><div class="copyText"><h1>Canvas和SVG的区别是什么?</h1><p>1. Canvas主要是用笔刷来绘制2D图形的。</p><p>2. SVG主要是用标签来绘制不规则矢量图的。</p><p>3. 相同点:都是主要用来画2D图形的。</p><p>4. 不同点:Canvas画的是位图,SVG画的是失量图。</p><p>5. 不同点:SVG节点过多时渲染慢,Canvas性能更好一点,但写起来更复杂。</p><p>6. 不同点:SVG支持分层和事件,Canvas不支持,但是可以用库实现</p></div></body><script>// 复制文本function copyText(){var div = document.querySelector(".copyText")// 安全域下使用 navigator.clipboard 提升效率if (navigator.clipboard && window.isSecureContext) {var texts=div.innerText// navigator clipboard 向剪贴板写文本navigator.clipboard.writeText(texts).then(function() {alert("复制成功")}, function() {alert("复制失败")});}else{// document.execCommand 已被弃用,所以首选 navigator.clipboardvar rangeif (document.body.createTextRange) {range = document.body.createTextRange();range.moveToElementText(div);range.select();} else if (window.getSelection) {var selection = window.getSelection();range = document.createRange();range.selectNodeContents(div); // 创建选取内容范围selection.removeAllRanges(); // 清除已选择的内容selection.addRange(range); // 添加选取内容,模拟用户选取/*if(selection.setBaseAndExtent){selection.setBaseAndExtent(text, 0, text, 1);}*/} else {console.warn("none");}document.execCommand('copy'); // 触发复制事件alert("复制成功")document.execCommand("unselect", "false", null) // 取消选取区域}}</script></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。