JavaScript Clipboard 复制到剪切板功能

JavaScript About 846 words

Clipboard

navigator.clipboard.writeText("复制的内容")
    .then(() => {
        console.log("success");
    })
    .catch(reason => {
        console.log("error", reason);
    })

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<pre>
    <code id="code">
        navigator.clipboard.writeText("abcd")
    </code>
</pre>
<button onclick="doCopy(this, 'code')">Copy</button>
<script>
    function doCopy(element, id) {
        let codeElement = document.getElementById(id);
        navigator.clipboard.writeText(codeElement.textContent)
            .then(() => {
                console.log("success");
            })
            .catch(reason => {
                console.log("error", reason);
            })
    }
</script>
</body>
</html>

兼容性

https://caniuse.com/?search=navigator.clipboard

Views: 138 · Posted: 2024-09-10

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh