如何从 contenteditable div 复制 innertext?

How to copy innertext from a contenteditable div?

我有一个 contenteditable div,其初始内容是在运行时在服务器端设置的。然后用户需要能够在客户端进行编辑(因此可以进行内容编辑)。然后用户需要能够使用复制按钮复制 txtDiv 的编辑内容。

我试过下面的代码,但我需要它在 txtDiv 而不是 myInput 上工作。此外,如果我将 runat="server" 添加到 myInput.

,它对 myInput 不起作用

这按预期工作:

<script>
function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied");
}
</script>
    <!-- The text field -->
<input type="text" value="Hello World" id="myInput">


<!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>

我需要这个来工作:

<script>
function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("txtDiv").innertext;

  /* Select the text field */
  copyText.select();

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied");
}
</script>
    <!-- The text field -->
    <div id="TxtDiv" runat="server" AutoPostBack="True" aria-multiline="True" contenteditable="true" 
        style="z-index: 1; text-align:left; border:1px solid; overflow-y:scroll; height: 82px"></div>

<!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>

然后用户需要能够使用复制按钮复制 txtDiv 的编辑内容。

@Wei 在 https://forums.asp.net/t/2157977.aspx?How+to+copy+innertext+from+a+contenteditable+div+whose+initial+value+is+set+on+the+server+side+ 提供的部分答案让我完成了 90% 的答案。我唯一要添加的是两件事:1) 后面的代码中的控件名称中不允许使用连字符,因此如果您想从后面的代码访问该控件,则不能使用 "my-div"。 2) div 需要在客户端,你不能在后面的代码中设置 innerhtml 属性 因为控件不在服务器上。为了解决这个问题,我将一个跨度和一个服务器文字放入 div 的内部 html。现在我可以使用在后面的代码中构造的 html 设置文字的文本,它会在 div.

中产生所需的输出

最终有效的代码是:

<script>
  function copy() {
      var target = document.getElementById('mydiv');
      var range, select;
      if (document.createRange) {
        range = document.createRange();
        range.selectNode(target)
        select = window.getSelection();
        select.removeAllRanges();
        select.addRange(range);
        document.execCommand('copy');
        select.removeAllRanges();
      } else {
        range = document.body.createTextRange();
        range.moveToElementText(target);
        range.select();
        document.execCommand('copy');
      }
    }
</script>

<div id="mydiv" contenteditable="true" style="z-index: 1; text-align:left; border:1px solid; overflow-y:scroll; height: 82px"><span><asp:Literal ID="Literal1" runat="server"></asp:Literal></span></div>

<div><input onclick="copy()" type="button" value="Copy" /></div>

后面的代码是:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Literal1.text="<span style='color:#d9534f'> Red </span><span style='color:#0275d8'> Blue </span>"

    End Sub

这不仅允许您复制 div 的内容,而且您可以在 div 中使用几种不同颜色的文本,您还可以编辑 [=23] 的内容=] 编辑后的版本将被复制。