提交表单时使用jquery保存和检索窗口滚动窗口位置的最佳方法

时间:2014-11-15 18:46:49

标签: javascript php jquery html

我是jquery的新手。我正在使用php和jquery来完成一些任务。当我通过单击图像按钮提交表单时,我想获得窗口的垂直滚动条位置并将其保存在浏览器中。然后我想从窗口中检索它并在页面重新加载后设置滚动条位置

$(document).ready(function(){
$("#button").click(function(){
  // get the scroll bar position 
  // save the scroll bar position
});
});


$(document).ready(function(){
   If scroll bar position available{
// retrieve the scroll bar position 
// set  the scroll bar position
}
});

我找到了一些解决方案,其中滚动条位置在隐藏的输入字段中传递,然后他们通过获取POST变量来设置位置。我不需要在隐藏的输入文件中传递它 可能吗?你能帮我吗? 提前致谢

2 个答案:

答案 0 :(得分:1)

作为建议,使用JQuery的data()

保存数据:

$("#button").data("KEY","VALUE");

获取数据:

var key=$("#button").data("KEY");

通过data(),您可以存储滚动位置,并在需要时获取它。

答案 1 :(得分:1)

感谢您的回复。我终于使用sessionStorage做到了。这是代码

$(document).ready(function(){
  $(":image").click(function(){
        sessionStorage.scrolly=$(window).scrollTop();
  });

  if (sessionStorage.scrolly) {
        $(window).scrollTop(sessionStorage.scrolly);
        sessionStorage.clear();
  }
});