复制文本
<button onclick="copyText()">复制文本</button>
<script>
function copyText() {
navigator.clipboard.writeText("这是复制的内容")
}
</script>
复制HTML
通过指定的文本类型来构建Blob、在结合 navigator.clipboard.write 将带有样式的 HTML 内容写入剪贴板
<button onclick="copyHTML()">复制HTML</button>
<script>
function copyHTML() {
const data = new Blob([' <b style="color: red;">这就是个例子</b>'], { type: "text/html" })
const item = new ClipboardItem({ 'text/html': data })
navigator.clipboard.write([item])
}
</script>
复制图片
单图片复制
获取到图片的响应对象,从响应对象中获取图片的 Blob 数据。
使用 ClipboardItem 创建一个包含图片 Blob 数据的 ClipboardItem 对象
在使用 navigator.clipboard.write 方法将包含图片的剪贴板项写入剪贴板
<button onclick="copyImage()">复制图片</button>
<script>
async function copyImage() {
const res = await fetch('./image.png');
const bold = await res.blob()
const item = new ClipboardItem({ 'image/png': bold })
navigator.clipboard.write([item])
}
</script>
全代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
width: 800px;
margin: 0 auto;
}
.content {
padding-top: 100px;
}
.editor {
width: 100%;
height: 160px;
margin-top: 10px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="content">
<button onclick="copyText()">复制文本</button>
<button onclick="copyHTML()">复制HTML</button>
<button onclick="copyImage()">复制图片</button>
<div class="editor" contenteditable="true"></div>
</div>
<script>
function copyText() {
navigator.clipboard.writeText("这是复制的内容")
}
function copyHTML() {
const data = new Blob([' <b style="color: red;">这就是个例子</b>'], { type: "text/html" })
const item = new ClipboardItem({ 'text/html': data })
navigator.clipboard.write([item])
}
async function copyImage() {
const res = await fetch('./image.png');
const bold = await res.blob()
const item = new ClipboardItem({ 'image/png': bold })
navigator.clipboard.write([item])
}
</script>
</body>
</html>