我正在尝试制作一个按钮来选择<code>
元素的内容。然而,它不起作用,我得到了"content.select()
不是函数
<body>
<div>
<button type="button" id="copyButton" class="btn btn-primary" onclick="copyConfig()">Copy Config</button>
<br><br>
<pre><code id="contentCfg">{{ content }}</code></pre>
</div>
</body>
<script>
function copyConfig() {
const content = document.getElementById("contentCfg").textContent;
content.select();
content.setSelectionRange(0, 99999);
document.execCommand("copy");
}
</script>
不知道为什么这不起作用,{{ content }}
会自动由我的模板serve.r 填充文本
您实际上可以使用Document.createRange()
、Range.selectNodeContents()
和Window.getSelection()
来解决此问题,从而避免不必要的DOM操作。
请参阅MDN上的示例或此问题中的讨论:选择元素中的文本(类似于用鼠标突出显示(
function copyConfig() {
const contentNode = document.getElementById("contentCfg")
const range = document.createRange();
range.selectNodeContents(contentNode);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
}
const copyButton = document.getElementById('copyButton');
copyButton.addEventListener('click', copyConfig);
<div>
<button type="button" id="copyButton" class="btn btn-primary">Copy Config</button>
<br><br>
<pre><code id="contentCfg">{{ content }}</code></pre>
</div>
最终通过将js更改为这个来修复它(添加了elem部分(
function copyConfig() {
const content = document.getElementById("contentCfg").textContent;
const elem = document.createElement("textarea");
document.body.appendChild(elem)
elem.value = content;
elem.select();
elem.setSelectionRange(0, 99999);
document.execCommand("copy");
document.body.removeChild(elem);
}