首页 > 解决方案 > 如何在将字符串插入到光标当前位置的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>

标签: javascripthtmlcss

解决方案


更改insertTextinsertHTML

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>


推荐阅读