首页 前端知识 jquery实现表格横向纵向滚动(横向滚动时左侧固定前几列)

jquery实现表格横向纵向滚动(横向滚动时左侧固定前几列)

2024-01-31 12:01:11 前端知识 前端哥 837 641 我要收藏

html

<div class="mybox" style="height: 100vh;position: absolute;top: 0;"></div>
  <div class="table-list">
    <table>
     <thead>
        <tr>
          <th>表头</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>内容</td>
        </tr>
      </tbody>
    </table>
  </div>

css

	.table-list thead tr{background: #eef3f7;}
	.table-list{width: 100%; overflow: auto; }
	.table-list th,.table-list td{white-space: nowrap;}
	.table-list th { background-color: #fff; position: sticky; top: 0px; }
	.table-list th:nth-child(-n+5) { position: sticky; top: 0px; z-index: 10; }
	.table-list td:nth-child(-n+5) { background-color: #fff; position: sticky; }
	.table-list th:first-child,.table-list td:first-child{ left: 0px; }

js

	// 表格滚动
	roll()
	$(window).resize(function(){
		roll()
	})
	function roll(){
		var myheight = $('.mybox').height();
		var tableheight = $('.table-list table').height();
		var conheight = myheight-178 // 178是查询条件的固定高度,减去之后就是表格的高度自适应
		if(tableheight<=conheight){
			conheight = tableheight;
		}
		$('.table-list').height(conheight);
		var $fixedColumns = $('table tr').find('td').slice(1, 5);
		// 计算每列的宽度
		var columnWidths = [];
		var fixedWidth = 0;
		$fixedColumns.each(function(index) {
			fixedWidth += parseInt($(this).outerWidth());
			columnWidths.push(fixedWidth);
		});
		$('table tr').each(function() {
			$(this).find('td').slice(1, 5).each(function(index) {
				$(this).css('left', columnWidths[index] + 'px');
			});
			$(this).find('th').slice(1, 5).each(function(index) {
				$(this).css('left', columnWidths[index] + 'px');
			});
		});
	}
转载请注明出处或者链接地址:https://www.qianduange.cn//article/955.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!