gpt4 book ai didi

javascript - content.select() 不适用于 元素

转载 作者:行者123 更新时间:2023-12-05 06:54:50 24 4
gpt4 key购买 nike

我正在尝试制作一个按钮来选择 <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 操作。

参见 example on MDN或讨论这个问题: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>

关于javascript - content.select() 不适用于 <code> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65452693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com