Layui表格过长,需固定悬浮表头在顶部

在这里插入图片描述

前要:后台系统适用的是Layui中间库,表格没有分页的,所以表格太长,需求是滚动到一定的位置的时候筛选表单和表格的表头进行固定浏览器顶端!

方法一:插入class类

let headerTop = $('#editForm').offset().top;
	$(window).scroll(function () {
    
    
		if ((headerTop - $(window).scrollTop()) < 0) {
    
     
		     $('#editForm').addClass('addFilexd'); 
		     $('#editForm').addClass('layui-table-header'); 
		 } else {
    
    
		     $('#editForm').removeClass('addFilexd');
		     $('#editForm').removeClass('layui-table-header');
		 }
	});
.addFilexd{
    
    
	position: fixed;
	top: 0;
	z-index: 999;
	background: #fff;
	width: 100%;
}
.layui-table-header{
    
    
	position: fixed;
	top: 100px;
	z-index: 999;
}

思路:定义表单和表头的类,当滑动的距离与原来表单距离顶端的距离相差<0的时候插入对于的类样式,否则去掉!

方法二:插入对应的内联样式
原因:上面插入的class相对于Layui内置的样式优先级不够高,没有作用起来!所以还是要插入对应的内敛样式!

let headerTop = $('#editForm').offset().top;
	$(window).scroll(function () {
    
    
		if ((headerTop - $(window).scrollTop()) < 0) {
    
     
		    // $('#editForm').addClass('addFilexd'); 
			$('#editForm').css({
    
    position: 'fixed',top: '0','z-index': '999',background: '#fff','width': '100%'}); 
			$('.layui-table-header').css({
    
    position: 'fixed',top: '100px','z-index': '999'}); 
		 } else {
    
    
		    // $('#editForm').removeClass('addFilexd');
			$('#editForm').css({
    
    position: 'unset',top: '0','z-index': '0'}); 
			$('.layui-table-header').css({
    
    position: 'unset',top: '100px','z-index': '0'}); 
		 }
	});

方法三:使用表格自带的回调

思路:问题的关键是如何知道表头是否超出可视范围,首先我们需要知道表头到文档顶部的距离,这个距离是不会变的(除非操控DOM),然后监听滚动条滚动的距离。如果前者减去后者小于0,则表示离开了可视范围

先在Layui表格渲染完成的回调函数里写

done: function () {
    
    //表格渲染完成的回调函数
       var headertop = $(".layui-table-header").offset().top//获取表头到文档顶部的距离
       $(window).scroll(function () {
    
    //开始监听滚动条                        
           if (headertop - $(window).scrollTop() < 0) {
    
        //超过了                              
              $(".layui-table-header").addClass('table-header-fixed')//添加样式,固定住表头
           }else {
    
    //没超过
               $(".layui-table-header").removeClass('table-header-fixed')//移除样式
           }
       })
}

然后在head标签里添加style,即可完成

<style type="text/css">
    .table-header-fixed {
    
    
        position: fixed;
        top: 0;
        z-index: 99
    }
</style>

猜你喜欢

转载自blog.csdn.net/weixin_45788691/article/details/127755348