我正在尝试制作一个按钮来选择 a 的内容<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 }}
我的模板服务器自动填充文本
你实际上可以使用以下方法解决这个问题Document.createRange() https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange, Range.selectNodeContents() https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents and Window.getSelection() https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection从而避免不必要的 DOM 操作。
See the MDN 上的示例 https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents#Example或在这个问题中的讨论:选择元素中的文本(类似于用鼠标突出显示) https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)