jquery - 在 contenteditable 中交替字体颜色
问题描述
您好,我正在尝试让我的字体颜色在我输入时交替显示。但是,当我输入新文本时,我的文本遵循相同的颜色并且不会交替出现。我想知道为什么当我输入新字母时它没有交替。非常感谢您的帮助。
$("span").each(function(index) {
var originalText = $(this).text();
var newText = "";
for (var i = 0; i < originalText.length; i++) {
if (i % 2 === 0)
newText += "<span>" + originalText.charAt(i) + "</span>";
else
newText += originalText.charAt(i);
}
$(this).html(newText);
});
span {
color: red;
font-weight: bold;
}
span>span {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable=true>
<span>this is just a test.</span>
<br/>
<span>color color color</span>
</div>
解决方案
document.getElementById("inputArea").addEventListener('input',alternateColor);
alternateColor();
function alternateColor() {
$( "span" ).each(function( index ) {
var originalText = $( this ).text();
var newText = "";
for( var i = 0; i < originalText.length; i++)
{
if (i % 2 === 0)
newText += "<span>" + originalText.charAt(i) + "</span>";
else
newText += originalText.charAt(i);
}
$( this ).html(newText);
});
}
span
{
color: red;
font-weight: bold;
}
span > span
{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id= "inputArea" contenteditable=true>
<span>this is just a test.</span>
<br/>
<span>color color color</span>
</div>
推荐阅读
- javascript - Flatpickr 甲酸盐与 12 小时以及 AM/PM
- sql - 以字符串为参数的存储过程不起作用-SQL
- performance - 无法在 Jmeter 中并行运行多个线程组
- python - Docker + pubsub + subprocess 挂起且没有错误
- mysql - 如何将mysql查询转换为sequelize语法?
- python - if-if-else 和 if-elif-else 在 while 循环中的行为差异
- c - 每个函数在 C 中在运行时打印调试语句
- reactjs - Gatsby 如何使用 gatsby build 命令生成的公用文件夹中的 .env.productionn 环境文件?
- string - 函数定义中无法识别字符串
- sql - 使用 JOIN 更新多个 JSON 节点