javascript - 复制文本按钮不起作用,我一直在说空白不是功能
问题描述
所以我试图制作一个按钮,将 ID 为“n”的段落标签复制到剪贴板上,但我不断收到错误消息,说选择不是函数,其他东西不是函数,我在做什么错误的?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320, initial-scale=1">
<meta charset="utf-8">
<style>
body, html {
min-width: 100%;
min-height: 100%;
margin: 0;
padding: 0;
font: Arial 14px;
}
</style>
<script>
function n() {
var ntext = document.getElementById("n");
ntext.select();
ntext.setSelectionRange(0, 99999);
document.execCommand("copy");
alert("could be copied")
}
</script>
</head>
<body>
<input>
<button onclick="n()">
Click
</button>
<p id="n">
ee
</p>
</body>
</html>
解决方案
这仅适用于输入字段。对你来说,因为你是从一个段落中复制的,你可以试试这个:
<!DOCTYPE html>
<html>
<body>
<script>
function CopyToClipboard(id){
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
</script>
<p id="sample">Hello World</p>
<a href="#" onclick="CopyToClipboard('sample');return false;">Copy Text</a>
</body>
</html>
您现在可以根据自己的喜好编辑它。
推荐阅读
- python - 如何通过机器人回复触发对话处理程序?[电报机器人] [Python] [python-telegram-bot]
- javascript - 应用程序屏幕变为空白并显示错误(类型错误:分配给常量)
- typescript - Nestjs TypeORM BasicEntity 不遵守命名约定
- html - 如何为硒网络抓取找到正确的 html 元素?
- python - 从文本文件中删除一行中的特定字符
- r - R Shiny visNetwork_2.1.0 中的错误与 visHierarchicalLayout 产生难以辨认的可视化?
- flash - Flash CS6 文件中消失的图形元素
- r - R SQLITE 表更新
- html - 如何使用 HTML 将文本和图像放置在形状内?
- domain-driven-design - 如何处理潜在的域(集成)事件顺序混乱?