如何用内联JavaScript实现HTML表格行点击切换背景色
实现表格行点击切换高亮效果
我来帮你搞定这个问题!你当前的代码只能让点击的单行变成蓝色,但之前选中的行不会恢复默认样式对吧?其实只需要添加一个简单的JavaScript函数,先重置所有表格行的背景色,再给当前点击的行设置高亮即可。
基础实现方案
<table> <tr onclick="highlightRow(this)"> <td>row1</td> <td>content1</td> </tr> <tr onclick="highlightRow(this)"> <td>row2</td> <td>content2</td> </tr> <tr onclick="highlightRow(this)"> <td>row3</td> <td>content3</td> </tr> </table> <script> function highlightRow(selectedRow) { // 1. 获取表格里所有的行元素 const allRows = document.querySelectorAll('table tr'); // 2. 遍历所有行,把背景色重置为默认样式(空值表示继承父元素样式,也可以改成具体颜色比如'white') allRows.forEach(row => { row.style.backgroundColor = ''; }); // 3. 给当前点击的行设置蓝色背景 selectedRow.style.backgroundColor = 'blue'; } </script>
优化建议(更符合前端最佳实践)
如果想让样式和逻辑分离,推荐用CSS类来控制高亮,后续修改样式会更方便:
<style> /* 定义高亮样式 */ .table-row-highlighted { background-color: blue; } </style> <table> <tr onclick="toggleRowHighlight(this)"> <td>row1</td> <td>content1</td> </tr> <tr onclick="toggleRowHighlight(this)"> <td>row2</td> <td>content2</td> </tr> </table> <script> function toggleRowHighlight(selectedRow) { const allRows = document.querySelectorAll('table tr'); // 先移除所有行的高亮类 allRows.forEach(row => { row.classList.remove('table-row-highlighted'); }); // 给当前行添加高亮类 selectedRow.classList.add('table-row-highlighted'); } </script>
特殊场景处理
如果你的表格包含表头(<th>所在的第一行),不想让表头被选中,可以修改获取行的代码:
// 只选中非表头的行 const allRows = document.querySelectorAll('table tr:not(:first-child)');
内容的提问来源于stack exchange,提问作者Shreenivas
相关产品推荐
相关产品推荐

