当前位置: 首页 > article >正文

JS 实现一键复制文本内容

1、演示:

2、代码

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>一键复制</title>
    <style>
        .container {
            display: flex;
            justify-content: center;
            >button {
                background-color: #fff;
                border: 2px solid #ccc;
                height: 32px;
                border-radius: 5px;
                padding: 5px 15px;
            }
            >span {
                line-height: 32px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <span>如:</span>
        <span id="text">生活如意,事业高升。</span>
        <button id="btn" onclick="copy()">一键复制</button>
    </div>
</body>
<script>
    function openMessage(value) {
        const msg = document.createElement('div');
        msg.style.height = '35px';
        msg.style.lineHeight = '35px';
        msg.style.padding = '5px 10px';
        msg.style.position = 'fixed';
        msg.style.top = '50%';
        msg.style.left = '50%';
        msg.style.transform = 'translate(-50%, -50%)';
        msg.style.backgroundColor = 'rgba(0, 0, 0, .3)';
        msg.style.textAlign = 'center';
        msg.style.color = 'white';
        msg.style.borderRadius = '15px';
        msg.textContent = value;
        document.body.appendChild(msg);

        setInterval(() => {
            document.body.removeChild(msg);
        }, 5000);
    }
    function copy() {
        const text = document.getElementById('text')
        const textarea = document.createElement('textarea');
        textarea.readOnly = 'readonly';
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        textarea.value = text.innerText;
        document.body.appendChild(textarea);
        textarea.select();
        const result = document.execCommand('Copy');
        if (result) {
            // console.log('复制成功');
            openMessage('复制成功')
        } else {
            openMessage('操作失败')
        }
        document.body.removeChild(textarea);
    }
</script>

</html>


http://www.kler.cn/a/158172.html

相关文章:

  • 面向注解编程—Spring 注解看这一篇就够了
  • 蓝桥杯算法心得——想吃冰淇淋和蛋糕(dp)
  • 迅速认识什么是格雷码,格雷码和二进制怎么进行转换
  • 华纳云:Tomcat无法加载css和js等静态资源文件怎么解决
  • Oracle之ORA-29275: 部分多字节字符
  • Ubuntu 2204 安装libimobiledevice
  • PIC12F1572-I/SN国产低成本32位MCU替换
  • 操作系统复习总结——文件管理
  • 如何判断服务器是否被CC攻击了,被CC了要如何防御
  • 食品行业研究:金枪鱼产业发展及市场消费分析
  • 11.30BST理解,AVL树操作,定义;快速幂,二分求矩阵幂(未完)
  • 矩阵的初等变换
  • 如何优雅的调用三方接口
  • JS中的 回调函数(callback)
  • k8s的部署管理以及prometheus相关监控
  • postgresql 将所有表的id列设置为自增主键,自增起始数值为该表的最大id
  • 微信小程序云开发报错
  • Native API 在 HarmonyOS 应用工程中的使用指导
  • Leetcode 2949. Count Beautiful Substrings II
  • mapbox实现框选要素