如何在将字符串插入光标的当前位置之前更改其颜色

问题描述 投票:0回答:1

我在尝试更改要添加到编辑器中的字符串的颜色时得到此输出。不考虑css部分。它被添加为简单的html。可能是什么问题?

some text <font color="green">ADD THIS VALUE</font> some text  and ...

这里是添加功能

function add_str(event) {
  event.preventDefault()
  var elt = document.getElementById("text_write");
  insertAtCursor(elt, "ADD THIS VALUE");
}

function insertAtCursor(myField, myValue) {
  myValue = myValue.fontcolor("green");
  if (myField.setRangeText) {
    myField.setRangeText(myValue)
  } else {
    document.execCommand('insertText', false, myValue);
  }
}

和html部分

<button onmousedown="add_str(event)">
add srting
</button>

<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text  and ...</div>

提前谢谢您

javascript html css
1个回答
0
投票

function add_str(event) {
  event.preventDefault()
  var coloredstring = "ADD THIS VALUE"
  var colorofstring = "green"
  var node = document.getElementById("text_write")
  var addedstring = `<span style="color:${colorofstring}">${coloredstring}</span>`
  node.innerHTML = node.innerHTML + addedstring
}
<button onmousedown="add_str(event)">
add srting
</button>

<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text  and ..</div>

字体标签不再适用于html5,我使用span标签进行了一些破解

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