如何使用JavaScript复制内部HTML,但没有html简写?

问题描述 投票:0回答:4
javascript html copy-paste
4个回答
0
投票

问题是您试图在应该分配 HTML 节点的地方分配一个字符串。

“innerText”就是您要找的。

document.getElementById("copied-message").innerText = "Copied";

innerHTML 需要 DOM 中已存在的元素的实例。您可以通过克隆 DOM 中已有的元素并将innerHTMl 值设置为该元素的副本来测试这一点。


0
投票

您可能想使用

HTMLElement.innerText
,但我将您链接到
HTMLElement.textContent
的 MDN 文档,因为它讨论了两者之间的一些细微差别。


0
投票

函数copyHtml() { var copyText = document.getElementById("代码输出").innerHTML;

// Create a temporary textarea element
var textarea = document.createElement("textarea");

// Set its value to the text you want to copy, with regular tags
textarea.value = copyText.replace(/&lt;/g, "<").replace(/&gt;/g, ">");

// Append the textarea to the document
document.body.appendChild(textarea);

// Select the text and copy it to the clipboard
textarea.select();
document.execCommand("copy");

// Remove the temporary textarea
document.body.removeChild(textarea);

document.getElementById("copied-message").innerHTML = "Copied";

}


0
投票

您可以使用此库更轻松地执行此类操作CopyShareify

© www.soinside.com 2019 - 2024. All rights reserved.