首页 > 解决方案 > CSS 冻结了带有水平滚动的表格的第一列。滚动位于 HTML 页面的主体上

问题描述

对于具有可滚动的冻结列的表,我已经看到了无数的解决方案,例如:

如何创建具有固定/冻结左列和可滚动正文的 HTML 表格?

但我所追求的是将滚动放在页面(正文)上,而不是放在桌子上或桌子周围的容器上。

编辑——它只是一个基本的 HTML 表格,它太大而无法完全显示,所以有一个水平滚动。在页面主体上进行水平滚动的原因是用户不必滚动到页面底部就可以水平滚动。

        .stickyCol2 tr th:nth-child(1),
        .stickyCol2 tr td:nth-child(1){    
          position: absolute;
          width: 50px;
          left: 15px;
          top: auto;  
          background-color: #fff;
        }

        .stickyCol2 tr th:nth-child(2),
        .stickyCol2 tr td:nth-child(2){    
          position: absolute;
          width: 60px;
          left: 86px;
          top: auto;  
          background-color: #fff;
        }
 <div class="stickyCol2">
            <table>
               <thead>
                  <tr>
                     <th>item 1</th>
                     <th>item 2</th>
                     <th>item 3</th>
                 </tr>
              </thead>
              <tbody>        
                 <tr>
                   <td>item 1</td>
                   <td>item 2</td>
                   <td>item 3</td>
                </tr>
             </tbody>
         </table>
         </div>

js 小提琴 https://jsfiddle.net/uthz6c24/1/

标签: htmlcsscss-tables

解决方案


以下是一些工作代码以及可用于微调解决方案的说明。

主要思想是您将要固定的列的内容包装在span元素中,您将其固定在屏幕的左侧(使用 CSS)并赋予它们等于其内容的宽度(我在我的代码中只使用了一列)。

var cellWidth=$('th:first-child').width();
$('th:first-child, td:first-child').each(function() {
  $(this).wrapInner('<span></span>');
  $(this).find('span').attr('style', 'width:'+cellWidth+'px;');
})

您将 a 添加margin-left到表中,等于固定列的总宽度(如果必须,您必须使用 Javascript 计算),以便固定列不会与可滚动单元格内容重叠。

$('table').attr('style', 'margin-left:'+cellWidth+'px;');

之后,使用 jQuery,您可以检测 body 的滚动(或者对于溢出的容器,工作方式相同)并在 span 上应用 transform:translateY属性。

$(window).on('scroll', function() {
  var scr = -$(this).scrollTop();
  console.log(scr);
  $('th:first-child span, td:first-child span').css('transform', 'translateY(' + scr + 'px)');
})

这是一个工作小提琴,希望它能给你最初的推动。 https://jsfiddle.net/scooterlord/ndxjg1b0/21/


推荐阅读