2014-06-11 32 views
1

我创建了一个回文检查器。我想更进一步,并显示正在检查的比较字母。div中的彩色字母

enter image description here

HTML:

<p id="typing"></p> 
<input type="text" id="textBox" onkeyup="pal(this.value);" value="" /> 
<div id="response"></div> 
<hr> 
<div id="palindromeRun"></div> 

JS:

要做到这一点,我跑的递归检查......然后,如果它是一个回文,我跑colorLetters() ,我试图用绿色突出每个字母,因为它正在被检查。现在它只是用第一个字母重写palindromeRun的HTML。我知道这是因为我重置其HTML的方式。

我不知道如何抓住第一个和最后一个字母,只更改这些字母的CSS,然后在下一个setTimeout循环中增加i和j。

var timeout2 = null; 

function pal (input) { 
    var str = input.replace(/\s/g, ''); 
    var str2 = str.replace(/\W/, ''); 

    if (checkPal(str2, 0, str2.length-1)) { 
     $("#textBox").css({"color" : "green"}); 
     $("#response").html(input + " is a palindrome"); 
     $("#palindromeRun").html(input); 
     colorLetters(str2, 0, str2.length-1); 
    } 
    else { 
     $("#textBox").css({"color" : "red"}); 
     $("#response").html(input + " is not a palindrome"); 
    } 
    if (input.length <= 0) { 
     $("#response").html(""); 
     $("#textBox").css({"color" : "black"}); 
    } 

} 

function checkPal (input, i, j) { 
    if (input.length <= 1) { 
     return false; 
    } 
    if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) { 
     return true; 
    } 
    else { 
     if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) { 
      return checkPal(input, ++i, --j); 
     } 
     else { 
      return false; 
     } 
    }        
} 

function colorLetters(myinput, i, j) { 
    if (timeout2 == null) { 
     timeout2 = setTimeout(function() { 
      console.log("called"); 
      var firstLetter = $("#palindromeRun").html(myinput.charAt(i)) 
      var secondLetter = $("#palindromeRun").html(myinput.charAt(j)) 

      $(firstLetter).css({"color" : "red"}); 
      $(secondLetter).css({"color" : "green"}); 

      i++; 
      j++; 
      timeout2=null; 
     }, 1000); 
    } 
} 

中学:如果可能的话,我只是想拥有它颜色的用户正在输入...我意识到这将需要每个keyup一个setTimeout,而且我不知道如何字母写这个。

enter image description here

回答

1

从周围的人物不同风格的一封信,你需要用它自己的,通常是span元素的元素。参看Is it possible to apply different styles to different letters in word?

对于构成input元素的值的字母,您无法这样做,因为该值被浏览器视为纯文本。但是,如果您使用用户可编辑的元素(使用contentEditable属性),则可以将每个字符放在内部元素中,但您需要实现一个小型编辑器或使用合适的库。