想在一个网页的文本框里实现类似Excel单元格那种输入数字和运算符即能计算的功能(=12+21-10 然后回车即计算出:23)
规则是:文本框里先输等号,然后是数字,接着是运算符,然后再是运算符,即:=12+5+56-5…… 回车后得出结果放在文本框里。

解决方案 »

  1.   

    可以的,加个事件,如onkeydown,然后检查是否按下回车,如果是,检查内容,是否以=开头,是就eval一下就OK了
      

  2.   


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    </head><body>
    <textarea rows="3" cols="20" id="calculator" style="background-color:#66FF99;"></textarea>
    <script>
    var cal = document.getElementById('calculator');
    cal.onkeydown = function(e){
    e = e || event;
    if(this.style.backgroundColor == '#f00')this.style.backgroundColor = '#66FF99';
    if(e.keyCode == 13){
    if(/^\=[\d,\+,\-,\*,\/,\(,\)]*$/.test(this.value)){
    this.value = eval(this.value.replace('=',''));
    }else{
    this.style.backgroundColor = '#f00';
    }
    return false;
    }
    }
    </script>
    </body>
    </html>只给你做了加减乘除。
    没做容错处理。
    大体就这么个意思
      

  3.   


    <script>
    var cal = document.getElementById('calculator');
    cal.onkeydown = function(e){
        e = e || event;
        if(this.style.backgroundColor == '#f00')this.style.backgroundColor = '#66FF99';
        if(e.keyCode == 13){
            if(/^[\d,\.,\+,\-,\*,\/,\(,\)]*\=$/.test(this.value)){
                this.value = eval(this.value.replace('=',''));
            }else{
                this.style.backgroundColor = '#f00';
            }
            return false;
        }
    }
    </script>