如何用javascript通过判断用户输入来改变表格颜色

我建了个contentedtitable的grid,我想通过点击该cell并输入"o"来改变该cell颜色.请问该怎么写javascript?

浮云间
浏览 654回答 2
2回答

30秒到达战场

题主试下这段代码:<style>#grid { margin:1em auto; border-collapse:collapse; }&nbsp;#grid td { cursor:pointer; width:30px; height:30px; border:1px solid #666; text-align: center;}</style><table id="grid" align="center">&nbsp; <tr>&nbsp; &nbsp; <td contenteditable="true">x</td>&nbsp; &nbsp; <td contenteditable="true">y</td>&nbsp; &nbsp; <td contenteditable="true">z</td>&nbsp; </tr></table><script>document.getElementById("grid").addEventListener("input", function(e) {&nbsp; &nbsp; if (e.target.innerHTML=="o") e.target.style.backgroundColor = 'lightblue';},false);</script>初始表格:更改内容后:根据题主提供代码修改如下:<html>&nbsp;<title>robot</title>&nbsp;<style>#mytable { margin:1em auto; border-collapse:collapse; }&nbsp;#mytable td { cursor:pointer; width:30px; height:30px; border:1px solid #666; text-align: center; contenteditable: true;}</style><table id="mytable" align="center"></table>&nbsp;<script>&nbsp;var mytable = document.getElementById('mytable');&nbsp;for (var i = 0; i < 10; i++) {&nbsp;&nbsp; &nbsp; var tr = mytable.insertRow();&nbsp;&nbsp; &nbsp; for (var j = 0; j < 10; j++) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var td = tr.insertCell();&nbsp; &nbsp; &nbsp; &nbsp; td.contentEditable = true;&nbsp; &nbsp; }&nbsp;}document.getElementById("mytable").addEventListener("input", function(e) {&nbsp; &nbsp; if (e.target.innerHTML=="o") e.target.style.backgroundColor = 'lightblue';},false);</script>&nbsp;</html>在题主使用的火狐浏览器下测试截图如下:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript