簡體   English   中英

單擊它時更改 td 背景顏色,但它的邊框除外

[英]Change td background color when click on it except its 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');
}

簡單:不要在單元格上設置邊框。
使用 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