我正在创建一个 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>
关于javascript - 为生成的文本创建复制剪贴板功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205340/