学习记录

复制的内容

 <p id="textToCopy">复制的内容</p><button class="btn-copy" onclick="copyText()">复制</button>
<style>
        .btn-copy {
            background-color: #4CAF50; /* 绿色背景 */
            border: none; /* 去掉边框 */
            color: white; /* 白色文字 */
            padding: 10px 20px; /* 内边距 */
            text-align: center; /* 文字居中 */
            text-decoration: none; /* 去掉下划线 */
            display: inline-block; /* 行内块元素 */
            font-size: 16px; /* 字体大小 */
            margin: 4px 2px; /* 外边距 */
            cursor: pointer; /* 鼠标指针 */
            border-radius: 8px; /* 圆角边框 */
            transition: background-color 0.5s; /* 背景颜色过渡效果 */
        }

        .btn-copy:hover {
            background-color: #45a049; /* 悬停时改变背景颜色 */
        }
    </style>
<script>
function copyText() {
  // 获取文本
  var text = document.getElementById("textToCopy").innerText;
  
  // 创建一个临时的输入框来存储文本
  var input = document.createElement("input");
  input.value = text;
  
  // 将输入框添加到页面,并选中文本
  document.body.appendChild(input);
  input.select();
  
  // 执行复制操作
  document.execCommand("copy");
  
  // 移除临时输入框
  document.body.removeChild(input);
  
  // 可以添加一些用户反馈,比如弹窗提示复制成功
  alert("文本已复制!");
}
</script>
最后修改:2024 年 10 月 29 日
如果觉得我的文章对你有用,请随意赞赏