7

Every time I type a character in an input field, I parse the expression so that I get:

  1. An array of tokens, i.e., tokenArray=[2, *, COS, (, 4, )]
  2. A corresponding array of token types, i.e., tokenType=[NUMBER, OPERATOR, FUNCTION, (, NUMBER, )]

I need to style each token (for instance assigning a different color to each token) based on its respective token type.

I have been able to easily style a dynamic copy of the input text in a different <div> (not the input text itself, which is what I am asking for help) as follows:

JavaScript:

function processExpression() {
    var userInput = document.getElementById('inputText').value;

        var resultOutput =  parse(userInput); //this generates the two arrays described above

        for (i in tokenArray) 
          newHTML += "<span style='color: " + colorMap[ tokenType[i] ] + " '>" +  tokenArray[i] + "</span>";

          document.getElementById('styledExpression').innerHTML = newHTML; 
}

HTML:

<input type="text" id="inputText" value="" placeholder="Type expression" size="40"
        onKeyDown="processExpression();" 
        onKeyUp="processExpression();"/>

<div id="styledExpression" value=""></div>

How can I style the input text directly in the input field where I type? Any JavaScript solution?

UPDATE

Tim's answer to the question replace innerHTML in contenteditable div provides some good help.

How would you modify http://jsfiddle.net/2rTA5/2/ to solve for when at every keydown, one reparses the entire editable? For example, imagine you type "=if(AND(3=2,A1:A4,OR(0,1)),5,6)" and, at every keydown the editable gets programmatically re-written (see token description above) and I lose the cursor.

How can this solution ignore the type of token or character or node and simply save and restore the absolute cursor (from the beginning of the ) position that was before the keydown?

4

3 回答 3

6

文本输入不支持样式化内容。故事结局。

一个常见的解决方案是contenteditable改用。

于 2012-05-05T20:25:29.587 回答
4

正如马特所说,<input>s 不支持样式内容。但是,一种可能的解决方案是使用<span>包含输入值的第二个,并在此处显示样式化的内容。如果这是不可接受的,那么contenteditable按照马特的建议使用。

于 2012-05-05T20:32:25.150 回答
2

如果它只是为了不重要的美学,你可以在它后面进行一些hack样式。

  • 使背景和文字<input>透明
  • <span>后面还有一个
  • 当的内容发生变化时更新<span>(使用适当的样式)的内容<input>

这是一个快速演示。

于 2012-05-05T20:53:48.810 回答