有人可以帮助我解决这个问题吗?我想我需要使用JS,但我对它的经验很少......所以我认为一些代码示例可能很有用。我得到了这样的简单表格(为了简化我没有复制表格的内容,因为它的代码很多而且不相关。
<div style="overflow:auto; height:600px; border:2px solid black; border-radius:5px; background:white">
<table style="width:100%; border-collapse:collapse">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
答案 0 :(得分:1)
在jQuery中(这将使用滚动位置保存cookie):
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(".yourTableContainerDIV").scrollTop( $.cookie("scroll") );
}
// On window unload, save cookie
$(window).unload(function() {
$.cookie("scroll", $(".yourTableContainerDIV").scrollTop() );
});
});
取自this answer,稍作修改。
修改强>
所以它不太有用。
第一个问题是,如果您使用的是this table,那么您需要阅读的不是容器DIV的scrollTop
,而是您需要查看的内容。
第二个问题是$(".scrollContent").scrollTop()
的值在调用$(window).unload()
之前变为0。当我像这样修改代码时:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(".yourTableContainerDIV").scrollTop( $.cookie("scroll") );
}
// Set i to the current scroll position every 100 milliseconds.
var i;
window.setInterval(function(){i=$(".scrollContent").scrollTop()}, 100);
// On window unload, save cookie.
$(window).unload(function() {
$.cookie("scroll", i);
});
});
效果很好!但是你已经调用了一个函数并且每十分之一秒设置一个值,这对于性能来说并不是太好。另一种方法是使用window.beforeUnload
,如下所示:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(".yourTableContainerDIV").scrollTop( $.cookie("scroll") );
}
});
window.onbeforeunload = function(){
$.cookie("scroll", $(".scrollContent").scrollTop());
return;
}
在大多数浏览器中都很有用,并且不涉及间隔,但它在Opera中不起作用。
希望这会有所帮助......
答案 1 :(得分:0)
这里有一个 100% 的工作解决方案,可以为需要的人提供持久的表格滚动位置。
// save position of table scroll
$(function () {
// If cookie is set, scroll to the position saved in the cookie.
if ($.cookie("scroll") !== null) {
$('#bScroll').scrollTop($.cookie("scroll"));
}
});
window.onbeforeunload = function () {
$.cookie("scroll", $('#bScroll').scrollTop());
return;
}
设置 tbody id='bScroll' 就可以了。
简单且保证不会失败。有很多“解决方案”,但除了这个,没有一个对我有用。