我有一个相当简单的需求要实现 - 在网页上放置一个按钮,点击后将包含图像和文本块复制到剪贴板。
我知道如何复制文本,也知道如何复制图像。据我所知,我不能同时进行两个操作。我是否遗漏了什么或者确实无法用JavaScript实现?有人能想到任何替代方案吗(如果是1995年,我会说Flash :-))。
非常感谢
我有一个相当简单的需求要实现 - 在网页上放置一个按钮,点击后将包含图像和文本块复制到剪贴板。
我知道如何复制文本,也知道如何复制图像。据我所知,我不能同时进行两个操作。我是否遗漏了什么或者确实无法用JavaScript实现?有人能想到任何替代方案吗(如果是1995年,我会说Flash :-))。
非常感谢
execCommand
和 Range/Selection
功能来实现此操作:
let button = document.querySelector('#copy-button');
button.addEventListener('click', function () {
let selection = window.getSelection();
let container = document.querySelector('.container');
if (selection.rangeCount > 0) {
selection.removeAllRanges();
}
const range = document.createRange();
range.selectNode(container);
selection.addRange(range);
document.execCommand("copy");
selection.removeAllRanges();
});
.container {
position: relative;
text-align: center;
color: white;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.top-left {
position: absolute;
top: 8px;
left: 16px;
}
.top-right {
position: absolute;
top: 8px;
right: 16px;
}
.bottom-right {
position: absolute;
bottom: 8px;
right: 16px;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<button id="copy-button">copy</button>
<div class="container">
<img src="https://moview.nl/wp-content/uploads/2018/04/Mountain_RvB-3-bw.jpg" alt="Snow" style="width:100%;">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>
execCommand
允许同时复制文本和图像,并且使用它时,记事本知道如何仅提取其中的文本。 - TechWisdom