首页 > 解决方案 > 在 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>

标签: jqueryhtmlcss

解决方案


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>


推荐阅读