1. 程式人生 > >原生js實現文字複製功能

原生js實現文字複製功能

廢話不多說,直接上程式碼

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    </head>

    <body>
        <div>歡迎光臨 9527</div>
        <button class="btn" onclick="copyThat()">Copy</button>

        <script>
            function copyThat() {
                var text = document.getElementsByTagName('div')[0].innerText;
                var eleInput = document.createElement('input');
                eleInput.value = text;
                document.body.appendChild(eleInput);
                eleInput.style.display = 'none';
                eleInput.select();
                document.execCommand("Copy")
            }
        </script>
    </body>

</html>