1. 程式人生 > 其它 >原生JS進行復制貼上功能

原生JS進行復制貼上功能

js實現文字複製貼上

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    div {
        width: 300px;
        height: 150px;
        border: 1px solid #eee;
        border-radius: 6px;
        cursor: pointer;
    }
</style>

<body>
    <div onclick="setText()" class="copy">我是即將被複制的文字內容</div>
    <div onclick="getText()" class="paste">點選貼上</div>
    <script>
        function setText() {
            var input = document.createElement("input")
            const text = document.querySelector(".copy").innerText
            input.value = text
            document.body.append(input)
            input.select(); 
            document.execCommand("Copy");
            input.parentNode.removeChild(input);
        }
        function getText() {
            navigator.clipboard.readText().then(text => {
                document.querySelector(".paste").innerText = text
            })
        }
    </script>
</body>

</html>