简体   繁体   English

单击它时更改 td 背景颜色,但它的边框除外

[英]Change td background color when click on it except its border

I have a function which changes cell bg color when click on it, but I want to function do nothing when click on cell's border.我有一个 function 单击它会更改单元格背景颜色,但我想 function 在单击单元格边框时什么也不做。

let table = document.getElementById('table');

table.onclick = function(event) {
  let target = event.target;

  while (target != this) {
    if (target.tagName == 'TD') {
      highlight(target);
      return;
    }
    target = target.parentNode;
  }
}

function highlight(td) {
  td.classList.toggle('purple');
}

simple: do not put borders on your cells.简单:不要在单元格上设置边框。
use css border-collapse: separate and border-spacing: ...使用 css border-collapse: separateborder-spacing: ...

 document.querySelector('#my-table').onclick = ({target}) => { if (.target.matches('td')) return target.classList.toggle('clickinout') }
 body { font-family: Arial, Helvetica, sans-serif; font-size: 16px; } table { border-collapse: separate; border-spacing: 1em; background-color: #2d2d9e;; margin: 2em; } td { border: none; background: whitesmoke; padding: .3em.4em; width: 3em; height: 2em; text-align: center; cursor: pointer; } td.clickinout { background: #dddd51; }
 <table id="my-table"> <tbody> <tr><td> a 1 </td><td> a 2 </td><td> a 3 </td><td> a 4 </td></tr> <tr><td> b 1 </td><td> b 2 </td><td> b 3 </td><td> b 4 </td></tr> <tr><td> c 1 </td><td> c 2 </td><td> c 3 </td><td> c 4 </td></tr> </tbody> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM