您好,我正在尝试键入时更改字体颜色。但是,当我输入新文本时,我的文本使用相同的颜色并且不会交替显示。我想知道为什么当我输入新字母时它不是交替出现的。非常感谢您的帮助。
$("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>
答案 0 :(得分:0)
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>