Haga clic en el botón para copiar al portapapeles

1. Escenario de demanda:

Haga clic en el botón Copiar para copiar el texto en el portapapeles

2. Implementación del código:

// Use la función de copia que viene con el navegador para copiar solo el contenido en el cuadro de texto, así que cree un cuadro de texto

// 用浏览器自带的copy功能只能复制文本框里面的内容,因此要创建文本框
function fallbackCopyTextToClipboard(text) {
    var result, textArea;
    textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    result = document.execCommand('copy');
    document.body.removeChild(textArea);
    return result;
}

// 复制到剪切板
function copyTextToClipboard(text) {
    if (navigator.clipboard) {
        return navigator.clipboard.writeText(text);
    } else {
        return fallbackCopyTextToClipboard(text);
    }
};

3. Haga clic en el botón para copiar:

$('#copy-citation-btn').on('click',function () {
   var textDom=$('.citation-style-item').filter(':visible');
   var text = textDom.text();
   if (copyTextToClipboard(text)) {
       alert('复制成功!')
   }
})

Supongo que te gusta

Origin blog.csdn.net/weixin_57092157/article/details/125079820
Recomendado
Clasificación