From 822e61f0eceacc2f535929b1b1c0b6294d1d08c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B4=AA=E6=98=8E=E6=96=B0?= Date: Sun, 26 Dec 2021 11:10:48 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20[=E4=BF=AE=E5=A4=8D]=20=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E7=B3=BB=E7=BB=9F=E5=89=AA=E8=B4=B4=E6=9D=BF=EF=BC=8C?= =?UTF-8?q?=E5=8F=AA=E9=80=82=E7=94=A8=E8=A2=AB=E6=8E=88=E6=9D=83=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E7=9A=84=E7=AB=99=E7=82=B9=EF=BC=8Chttp=E4=B8=8B?= =?UTF-8?q?=E4=B8=8D=E8=83=BD=E4=BD=BF=E7=94=A8=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- example/src/components/LayCode.vue | 35 ++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/example/src/components/LayCode.vue b/example/src/components/LayCode.vue index 3fa909b6..d5d59cec 100644 --- a/example/src/components/LayCode.vue +++ b/example/src/components/LayCode.vue @@ -34,9 +34,40 @@ const toggle = function () { const copy = function () { const foundCodes = meta.value.getElementsByClassName('language-html') - if (document.hasFocus()) { - const text = foundCodes[0].textContent || ""; + const foundCode = foundCodes[0]; + let successful = false; + // 使用原生系统剪贴板,只适用被授权安全的站点,http下不能使用 + if (navigator.clipboard && document.hasFocus()) { + const text = foundCode.textContent || ""; navigator.clipboard.writeText(text); + successful = true; + } else if (window.getSelection()){ + // 使用document.execCommand + // 代码div显示状态直接使用,隐藏状态则创建一个div + var range = document.createRange(); + let copyDiv; + if (show.value) { + range.selectNode(foundCode); + } else { + copyDiv = document.createElement('div'); + copyDiv.innerHTML = foundCode.innerHTML; + copyDiv.style.position="fixed"; + copyDiv.style.left="-9999px"; + document.body.appendChild(copyDiv); + range.selectNode(copyDiv); + } + window.getSelection()?.addRange(range); + try { + successful = document.execCommand('copy'); + } catch(err) { + successful = false; + console.error(err); + } + window.getSelection()?.removeAllRanges(); + copyDiv?.remove(); + } + + if (successful) { layer.msg("复制成功", { icon : 1, time: 1000}, ()=>{}) } else { layer.msg("复制失败", { icon : 2, time: 1000}, ()=>{})