带复制按钮的代码教学示例
一、HTML代码框示例
1.1 带复制按钮的代码框
这是一个带有复制按钮的代码框:
npm install express
npm install mongoose
npm install cors
点击右上角的"复制"按钮,可以复制代码到剪贴板。
1.2 多行代码示例
创建Express应用的完整代码:
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
二、JavaScript复制功能
2.1 复制函数
添加以下JavaScript函数实现复制功能:
function copyCode(button) {
// 找到代码框
const codeBox = button.nextElementSibling || button.parentNode.querySelector("pre");
const code = codeBox.querySelector("code").textContent;
// 复制到剪贴板
navigator.clipboard.writeText(code).then(() => {
// 显示复制成功提示
const originalText = button.textContent;
button.textContent = "已复制!";
button.style.background = "#2196F3";
// 2秒后恢复原状
setTimeout(() => {
button.textContent = originalText;
button.style.background = "#4CAF50";
}, 2000);
}).catch(err => {
console.error("复制失败:", err);
button.textContent = "复制失败";
button.style.background = "#f44336";
});
}
2.2 完整HTML示例
完整的HTML页面包含复制功能:
<!DOCTYPE html>
<html>
<head>
<title>代码复制示例</title>
<style>
.code-box {
position: relative;
margin: 20px 0;
}
.code-box pre {
background: #f5f5f5;
padding: 20px;
border-radius: 5px;
overflow-x: auto;
margin: 0;
}
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
background: #4CAF50;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
font-size: 12px;
}
.copy-btn.copied {
background: #2196F3;
}
.copy-btn.error {
background: #f44336;
}
</style>
</head>
<body>
<div class="code-box">
<button class="copy-btn" onclick="copyCode(this)">复制</button>
<pre><code>npm install express</code></pre>
</div>
<script>
function copyCode(button) {
const code = button.parentNode.querySelector("code").textContent;
navigator.clipboard.writeText(code).then(() => {
button.textContent = "已复制!";
button.classList.add("copied");
setTimeout(() => {
button.textContent = "复制";
button.classList.remove("copied");
}, 2000);
}).catch(err => {
button.textContent = "复制失败";
button.classList.add("error");
});
}
</script>
</body>
</html>
三、使用说明
3.1 添加复制按钮
在每个代码框的HTML结构中添加:
<div style="position: relative;">
<button onclick="copyCode(this)" style="position: absolute; top: 10px; right: 10px;">复制</button>
<pre><code>你的代码在这里</code></pre>
</div>
3.2 添加JavaScript函数
在页面底部添加复制函数:
<script>
function copyCode(button) {
const codeBox = button.nextElementSibling || button.parentNode.querySelector("pre");
const code = codeBox.querySelector("code").textContent;
navigator.clipboard.writeText(code).then(() => {
button.textContent = "已复制!";
button.style.background = "#2196F3";
setTimeout(() => {
button.textContent = "复制";
button.style.background = "#4CAF50";
}, 2000);
}).catch(err => {
button.textContent = "复制失败";
button.style.background = "#f44336";
});
}
</script>
四、注意事项
- 复制功能需要浏览器支持Clipboard API
- 在HTTPS环境下更可靠
- 可以自定义按钮样式和位置
- 支持多行代码复制