如何在Bootstrap表格中实现类似Excel的高亮选中多行功能
实现效果说明
修改后的代码可实现类似Excel的表格行选中效果:
- 点击单行可切换选中状态
- 按住鼠标左键拖拽可连续选中多行
- 选中区域整体带有绿色外框,和Excel视觉表现一致
- 表格区域光标自动切换为十字选择样式,贴合Excel操作习惯
- 按住Ctrl键点击可实现多段不连续选中
完整实现代码
CSS 代码
/* 表格基础样式 */ #table { border-collapse: collapse; width: 100%; } td { border: 1px #DDD solid; padding: 5px; cursor: crosshair; /* 替换为十字选择光标 */ } /* 选中行基础样式,可自行调整背景色 */ .selected { background-color: #e8f0fe; color: #000; } /* 选中区域绿色外框效果 */ #table tr.selected td:first-child { border-left: 2px solid #21a865; } #table tr.selected td:last-child { border-right: 2px solid #21a865; } #table tr.selected:first-of-type, #table tr.selected + tr:not(.selected) { border-top: 2px solid #21a865; } #table tr.selected:last-of-type, #table tr:not(.selected) + tr.selected { border-bottom: 2px solid #21a865; }
JavaScript 代码
let isDragging = false; let startRow = -1; // 鼠标按下开始拖拽选中 $("#table tr").mousedown(function(e) { isDragging = true; startRow = $(this).index(); // 未按住Ctrl键时清空之前的选中状态 if (!e.ctrlKey) { $("#table tr").removeClass('selected'); } $(this).toggleClass('selected'); // 阻止默认文本选中行为,避免干扰框选效果 e.preventDefault(); }); // 鼠标移动过程中选中经过的连续行 $("#table tr").mouseover(function() { if (!isDragging) return; const currentRow = $(this).index(); const minRow = Math.min(startRow, currentRow); const maxRow = Math.max(startRow, currentRow); // 批量选中起止行范围内的所有行 $("#table tr").each(function(index) { if (index >= minRow && index <= maxRow) { $(this).addClass('selected'); } }); }); // 鼠标抬起结束拖拽 $(document).mouseup(function() { isDragging = false; startRow = -1; }); // 原有业务逻辑保留 $("#table tr").click(function(){ var value=$(this).find('td:first').html(); alert(value); }); $('.ok').on('click', function(e){ var selected = []; $("#table tr.selected").each(function(){ selected.push($('td:first', this).html()); }); alert(selected); });
HTML 代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <table id="table"> <tr> <td>1 Ferrari F138</td> <td>1 000€</td> <td>1 200€</td> <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td> <td>1</td> <td>F138</td> <td>Klik pre detaily</td> </tr> <tr> <td>2 Ferrari F138</td> <td>1 000€</td> <td>1 200€</td> <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td> <td>1</td> <td>F138</td> <td>Klik pre detaily</td> </tr> <tr> <td>3 Ferrari F138</td> <td>1 000€</td> <td>1 200€</td> <td>Model monopostu stajne Scuderia Ferrari pre sezónu 2013</td> <td>1</td> <td>F138</td> <td>Klik pre detaily</td> </tr> </table> <input type="button" name="OK" class="ok" value="OK"/>
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

