我有一个用户可以输入原始 HTML 的字段。这看起来像:
<input type="text" id="editor" value="<p>Hi,</p><p>Here is a <a href='domain.com'>link</a> I'd like you to visit.</p>" />
Run Code Online (Sandbox Code Playgroud)
现在,我需要一个“复制到剪贴板”按钮来获取该字段的内容,以便我们可以将其粘贴为格式化文本(不带 HTML 标记)。在上面的例子中,复制/粘贴输出应该是:
Hi,
Here is a [link][1] I'd like you to visit.
Run Code Online (Sandbox Code Playgroud)
我已经实现了“复制到剪贴板”按钮,如下所示:
let answer = document.getElementById("editor");
answer.select();
document.execCommand("copy");
Run Code Online (Sandbox Code Playgroud)
这会将输入的内容放在剪贴板上,但是当我将其粘贴到其他地方时,我会得到原始 HTML。
我需要某种方法将 HTML 转换为格式化文本,但我找到的唯一解决方案是这个,它不适用于链接:
有没有原生的 Javascript 方法可以做到这一点?如果没有,最好的解决方案是什么?
尝试使用Element.insertAdjacentHTML()
let answer = document.getElementById("editor");
let result = document.getElementById("result");
let button = document.getElementById("button");
button.onclick = function() {
answer.select();
document.execCommand("copy");
};
function conVert(event) {
event.preventDefault();
let val = answer.value
console.log(val)
result.insertAdjacentHTML('afterbegin', val);
// you can use event.target here to past it as formated to targeted element onpaste
}
// on button
buttonpaste.onclick = function(event) {
conVert(event)
}
//on paste
document.onpaste = function(event) {
console.log("Paste")
conVert(event)
};Run Code Online (Sandbox Code Playgroud)
#result {
min-height: 100px;
background-color: yellow
}
#result2 {
min-height: 100px;
background-color: gray;
}Run Code Online (Sandbox Code Playgroud)
<input type="text" id="editor" value="<p>Hi,</p><p>Here is a <a href='domain.com'>link</a> I'd like you to visit.</p>" />
<button id="button">COPY</button>
<button id="buttonpaste">PASTE</button>
<div id="result" contentEditable="true"></div>
<div id="result2" contentEditable="true"></div>Run Code Online (Sandbox Code Playgroud)