更新 2019.7.21 12:29閲覧 1170

テーブルのカーソル位置の行と列をハイライトするジャバスクリプト

012345
11-11-21-31-41-5
22-12-22-32-42-5
33-13-23-33-43-5
44-14-24-34-44-5
55-15-25-35-45-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)}); });

コメント

当フォームより収集される個人情報は、返信を要する際に使用されるものであり、法令に基づく行政機関等への提供を除き、ご本人の同意を得ずに第三者に提供することはありません。また、コメントが掲載される場合であってもメールアドレスが本サイト内に記載されることはありません。