如何突出显示HTML表格中的单元格

时间:2016-03-18 16:05:59

标签: javascript jquery html css

如何通过让用户选择它们来突出显示HTML表格中的单元格 - 就像在Excel中一样?

以下是3个显示我的意思的示例:enter image description here

2 个答案:

答案 0 :(得分:1)

这是可能性之一:

<table>
<tr>
<td>...</td>
<td>...</td>
</tr>
...
</table>

和JavaScript:

function toggleBG() {
   if(this.className.indexOf("yellowBG") >= 0) {
      var x = this.className;
      this.className = x.split("yellowBG").join(''); 
   } else {
      this.className += "yellowBG";
   }
}
var elem = document.getElementsByTagName('td');
for (var i = 0; i < elem.length; i++) {
    elem[i].addEventListener('click', toggleBG,, false);
}

和CSS:

.yellowBG {
   background: yellow;
}

答案 1 :(得分:0)

当用户点击单元格时,您只需要应用CSS类。您可以在第二次单击时删除该类。

试试这个:

// Wait until the DOM is loaded
window.addEventListener("DOMContentLoaded", function(){

  // Get all the td elements in an array
  var theCells = document.getElementsByTagName("td");
  
  // Loop through each td
  for(var i = 0; i < theCells.length; ++i){
    
     // Set up a click event handler for the td
     theCells[i].addEventListener("click", function(){
       
       // Check to see if the td has the class attribute applied already
       if(this.getAttribute("class") === "highlight"){
         // If so, remove it
         this.removeAttribute("class");
       } else {
         // If not, add it
         this.setAttribute("class", "highlight");     
       }
     });
  }
  
});
td{border:1px solid black;}
.highlight {background:#ff0;}
<table>
  <tr>
    <td>...</td>
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>
  <tr>
    <td>...</td>
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>
  <tr>
    <td>...</td>
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>  
  <tr>
    <td>...</td>
    <td>...</td>
    <td>...</td>
    <td>...</td>
  </tr>  
</table>

相关问题