使用浏览器自带功能实现一键复制

<!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>一键复制demo</title>
    <style type="text/css">
        .wrapper {
            position: relative;
        }

        #input {
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
            z-index: -10;
        }

        .btn{
            -webkit-touch-callout: none;

            -webkit-user-select: none;

            -khtml-user-select: none;

            -moz-user-select: none;

            -ms-user-select: none;

            user-select: none;

        }

        #text {
            -webkit-touch-callout: none;

            -webkit-user-select: none;

            -khtml-user-select: none;

            -moz-user-select: none;

            -ms-user-select: none;

            user-select: none;


        }
    </style>
</head>

<body>
    <div class="wrapper">
        <p id="text" onclick="sss()">我把你当兄弟dsadsadasdas你却想着复制我?</p>
        <input type="text" id="input">
        <button class="btn" onclick="copyText()">copy</button>
    </div>
</body>
<script>
    function copyText() {
        var text = document.getElementById("text").innerText;
        var input = document.getElementById("input");
        input.value = text; // 修改文本框的内容
        input.select(); // 选中文本
        document.execCommand("copy"); // 执行浏览器复制命令
        alert("复制成功");
    }
    function sss(params) {
        console.log(111);
    }

</script>

</html>

ps:中间有一个不可选中文档的css

 

posted @ 2021-11-22 14:57  启豪  阅读(494)  评论(0)    收藏  举报