繁体   English   中英

固定标题可滚动表-如何在页面加载时使用CSS jQuery保留水平滚动位置

[英]Fixed Header Scrollable Table - How to preserve horizontal scroll position using css jquery on page loads

我有一个带有水平和垂直滚动条的固定标题滚动表,目前可以对其进行排序, 但在加载页面时无法正确保留表的水平位置

使用以下内联css,我从php的隐藏输入(其值来自jquery代码)中获取scrollAmount其输入到内联css中

style="transform:translateX(<negative offset value of scrollAmount>)"

我的问题是如何使用CSS和jQuery正确维护水平滚动条溢出的表的滚动位置,而无需等待页面完全加载/完成渲染?

内联样式

transform:translateX(-<?=scrollAmount()?>px)

jQuery滚动位置功能

function setScroll(id_header, id_table)
        {
             $('div.'+id_table).on("scroll", function(){  //activate when #center scrolls
                    var left = $('div.'+ id_table).scrollLeft();  //save #center position to var left
                   $('div.'+id_header).scrollLeft(left);        //set #top to var left
                   $('#scrollamount').val(left);
                });

隐藏的输入HTML代码

<input type="hidden" id="scrollamount" name="scrollamount" value=<?=scrollAmount()?>"/>

PHP代码

 function scrollAmount()
    {
        if (isset($_POST['scrollamount']))
            return $_POST['scrollamount'];
        return "";
    }

问题在于,每次滚动时.scrollLeft()都会更改,因此您只需将其设置为滚动到的位置即可。 您可能可以使用jQuery找到表的位置,并在开始时将其设置为通用变量,然后再使用$('div.'+id_header).scrollLeft(globalLeftPosition)进行设置。 希望这可以帮助。

使用以下代码,我能够产生一种视觉上可接受的解决方案,使表格在水平方向上偏移用户的滚动量。

JS代码-在表完成获取/加载后在document.ready()上执行

//Translate 0px, undoing the original translation       
$('table#'+ id_table).attr("style", "transform:translateX(0px)");   
$('table#'+ id_header).attr("style", "transform:translateX(0px)");  

//Scroll left to the desired amount as defined in the hidden input `#scrollamount` 
$('div.'+ id_table).scrollLeft($('#scrollamount').val());
$('div.'+ id_header).scrollLeft($('#scrollamount').val());

HTML / PHP代码-固定的标题滚动表(标题和表主体)

<div class="summary_header">
<table id="summary_header" border=1 style="transform:translateX(-<?=scrollAmount()?>px)">
    ... <-----Table Header Definition
</table>
</div>

<div class="summary_table" style="overflow-x:scroll">     
<table id="summary_table" style="transform:translateX(-<?=scrollAmount()?>px)">
    ... <--Table Body Definition
</table>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM