更新 2019.7.21 12:29閲覧 1194テーブルのカーソル位置の行と列をハイライトするジャバスクリプト
| 0 | 1 | 2 | 3 | 4 | 5 |
| 1 | 1-1 | 1-2 | 1-3 | 1-4 | 1-5 |
| 2 | 2-1 | 2-2 | 2-3 | 2-4 | 2-5 |
| 3 | 3-1 | 3-2 | 3-3 | 3-4 | 3-5 |
| 4 | 4-1 | 4-2 | 4-3 | 4-4 | 4-5 |
| 5 | 5-1 | 5-2 | 5-3 | 5-4 | 5-5 |
<table class="table table-bordered table-dark text-center">
<tr>
<th>0</th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th>
</tr>
<tr>
<th>1</th><td>1-1</td><td>1-2</td><td>1-3</td><td>1-4</td><td>1-5</td>
</tr>
<tr>
<th>2</th><td>2-1</td><td>2-2</td><td>2-3</td><td>2-4</td><td>2-5</td>
</tr>
<tr>
<th>3</th><td>3-1</td><td>3-2</td><td>3-3</td><td>3-4</td><td>3-5</td>
</tr>
<tr>
<th>4</th><td>4-1</td><td>4-2</td><td>4-3</td><td>4-4</td><td>4-5</td>
</tr>
<tr>
<th>5</th><td>5-1</td><td>5-2</td><td>5-3</td><td>5-4</td><td>5-5</td>
</tr>
</table>
<script>
let t=document.querySelectorAll('td, th'), b=function (e, f=false)
{
for(j=e.parentNode.parentNode.rows.length; --j>=0;)
e.parentNode.parentNode.rows[j].cells[e.cellIndex].classList.toggle('bg-danger', f);
e.parentNode.classList.toggle('bg-warning', f);
e.classList.toggle('bg-dark', f);
};
for(i=t.length; --i>=0;)
{
t[i].onmouseover = function(){b(this, true)}
t[i].onmouseout = function(){b(this)}
}
</script>
また↓のように書くこともできた
let a=function(b, c=false)
{
for(j=b.parentNode.parentNode.rows.length; --j>=0;)
b.parentNode.parentNode.rows[j].cells[b.cellIndex].classList.toggle('bg-danger', c);
b.parentNode.classList.toggle('bg-warning', c);
b.classList.toggle('bg-dark', c);
}
document.querySelectorAll('td, th').forEach((e) =>
{
e.addEventListener('mouseover', () => {a(e, true)});
e.addEventListener('mouseout', () => {a(e)});
});