自学内容网 自学内容网

JS小应用:复制指定div的内容到剪贴板

要复制指定div的内容到剪贴板,可以使用以下JavaScript代码:

function copyDivContentToClipboard(divId) {
    // 获取div元素
    var div = document.getElementById(divId);
    if (!div) {
        return;
    }
    // 创建一个新的临时div来持有要复制的内容
    var tempDiv = document.createElement("div");
    tempDiv.style.position = "absolute";
    tempDiv.style.left = "-10000px";
    tempDiv.appendChild(div.cloneNode(true));
    document.body.appendChild(tempDiv);

    // 选中内容
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(tempDiv);
    selection.removeAllRanges();
    selection.addRange(range);

    // 复制到剪贴板
    var successful = false;
    try {
        successful = document.execCommand('copy');
    } catch (err) {
        console.log('Oops, unable to copy');
    }

    // 移除临时div
    document.body.removeChild(tempDiv);

    if (successful) {
        console.log('内容已复制到剪贴板');
    }
}

使用这个函数,只需传入你想要复制内容的div的ID即可。例如,如果你的div的ID是"myDiv",你可以这样调用函数:

copyDivContentToClipboard("myDiv");

比如:

<button class="base" onclick="copyDivContentToClipboard('myDiv');">复制</button>

---------------

本篇文章仅是小技巧,为那些新入行的朋友们做参考。不喜勿喷谢谢 ~


原文地址:https://blog.csdn.net/uuplay0216/article/details/140724793

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!