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



在将字符串添加到div之前,我试图更改字符串的颜色。但css部分没有考虑在内。它增加了

<span style="color:green">ADD THIS VALUE</span> 

在光标位置,而不是只添加蓝色的ADD THIS VALUE
我缺少什么?这是代码片段。

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>'
insertAtCursor(node, addedstring);
}
function insertAtCursor(myField, myValue) {
if (myField.setRangeText) {
myField.setRangeText(myValue)
} else {
document.execCommand('insertText', false, myValue);
}
}
<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>

insertText更改为insertHTML:

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>'
insertAtCursor(node, addedstring);
}
function insertAtCursor(myField, myValue) {
if (myField.setRangeText) {
myField.setRangeText(myValue)
} else {
document.execCommand('insertHTML', false, myValue);
}
}
<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>

最新更新