【问题标题】:Copy HTML content with Javascript, paste as formatted text使用 Javascript 复制 HTML 内容,粘贴为格式化文本
【发布时间】:2021-05-18 12:32:56
【问题描述】:

我有一个用户可以输入原始 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>" />

现在,我需要一个“复制到剪贴板”按钮,该按钮获取该字段的内容,以便我们可以将其粘贴为格式化文本(没有 HTML 标记)。在上面的例子中,复制/粘贴的输出应该是:

Hi,

Here is a [link][1] I'd like you to visit.

我已经实现了这样的“复制到剪贴板”按钮:

let answer = document.getElementById("editor");
answer.select();
document.execCommand("copy");

这会将输入的内容放在剪贴板上,但是当我将其粘贴到其他地方时,我会得到原始 HTML。

我需要一些方法将 HTML 转换为格式化文本,但我找到的唯一解决方案是这个,它不适用于链接:

enter link description here

有没有一种原生的 Javascript 方法可以做到这一点?如果没有,最好的解决方案是什么?

【问题讨论】:

  • 那么你需要将 HTML 转换为 Markdown 吗?
  • 我会尝试将其放在 contenteditable 元素中,然后选择要复制的内容

标签: javascript html


【解决方案1】:

试试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)
};
#result {
  min-height: 100px;
  background-color: yellow
}

#result2 {
  min-height: 100px;
  background-color: gray;
}
<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    相关资源
    最近更新 更多