javascript - 为生成的文本创建复制剪贴板功能
问题描述
我正在创建一个 lorem ipsum 生成器,并从中获得了很多乐趣。但是,我正在尝试创建一个按钮,您可以在其中复制生成的文本。我哪里错了?
我有一个单独的 javascript 文件,可以成功生成文本,只是想知道如何复制它
<body>
<center>
<h1 class="title">Lorem Ipsum Generator</h1>
<p class="description">A Harry Potter lorem ipsum generator.</p>
<form action="/" method="POST">
<input type="number" class="paragraph-number" name="numberOfParagraphs">
<input type="submit" value="Expecto Patronum!" class="generate-button">
<input type="reset" value="clear" class="generate-button">
</form> </center>
<center>
<div class="border"><div id="generated-text">
<div class='placeholder-div'></div>
</div>
</div>
<button onclick="copyPassage()" class="copy-button">Copy text</button>
<script src=/generator.js>
function copyPassage() {
var copyText = document.getElementById("generated-text");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
</script>
解决方案
你很接近,但是有几件事出了差错。首先,DOM 是按顺序计算的,所以 onclick 处理程序不知道你的函数,因为它是在元素之后声明的;这导致了Uncaught ReferenceError: copyPassage is not defined。
接下来,使用错误的方法来实际选择文本。您使用.select()
了导致Uncaught TypeError: copyText.select is not a function。
相反,对于选择,您应该使用selectAllChildren
MDN。
在这里查看它的实际效果:
<script>
function copyPassage() {
var copyText = document.getElementById("generated-text");
window.getSelection().selectAllChildren(copyText);
document.execCommand("copy");
alert("Copied the text: " + copyText.innerText);
}
</script>
<button onclick="copyPassage()" class="copy-button">Copy text</button>
<div class="border">
<div id="generated-text">
<div class='placeholder-div'>Harry Potter</div>
</div>
</div>
推荐阅读
- kubernetes - traefik kubernetes crd 健康检查
- java - Android 服务在启动/恢复时短暂为空
- java - 用于命令行代码覆盖率计算的 Java 库?
- reactjs - .map 函数内的子组件显示所有子实例
- dockerfile - 为什么docker容器会自行退出
- php - 从 PHP 中的格式化纯文本中提取数据
- ios - 处理具有相同签名但不同参数的多个函数的最有效方法
- python - PyCharm 无法从 Docker 容器打开文件:没有这样的文件或目录
- unix - 防止在 AIX Unix 中创建空的 Tar 文件
- javascript - 当停止值之间的间隙相等时,为什么画布 gradient.addColorStop() 不居中?