javascript - 如何在将字符串插入到光标当前位置的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>
推荐阅读
- php - 在 php 中分别拆分 URL 和返回组件
- python - Python:从嵌套循环中打印数字序列
- javascript - 对于此默认设置,如何开始使用 express 和 nuxt/viue
- android - 为什么我们在 MVP 中定义视图和演示者的范围
- powershell - 在模块“Az.Compute”中找到“Get-azVM”命令,但无法加载该模块
- clojure - 如何查看 lein 任务的执行时间
- ios - 如何让颤振运行在带有 iPhone 的 OSX 上可靠地工作?
- c - 在 STM32H7 上接收 IrDA 消息
- python-3.x - 如果有像“pic.twitter.com”这样的网址,如何删除推文中的网址
- javascript - 如何用茉莉花单元测试情节点击事件