简体   繁体   English

重新加载网页,同时保存滚动位置并返回

[英]reload web page while saving scroll position and getting back to it

I am using this scrollTo plugin in my web application. 我在Web应用程序中使用 scrollTo插件。 the problem is i want to be able to refresh the page and save the scrolling position so that when page reloads its in the same position as before the reload. 问题是我希望能够刷新页面并保存滚动位置,以便页面重新加载时与重新加载之前的位置相同。 any idea how can i achive this one? 知道我该如何实现吗? thx... for convenience im ading the plugin's code here : thx ...为方便起见,在此处将插件的代码添加进来:

$.fn.scrollTo = function( target, options, callback ){
  if(typeof options == 'function' && arguments.length == 2){ callback = options; options = target; }
  var settings = $.extend({
    scrollTarget  : target,
    offsetTop     : 50,
    duration      : 500,
    easing        : 'swing'
  }, options);
  return this.each(function(){
    var scrollPane = $(this);
    var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
    var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top + scrollPane.scrollTop() - parseInt(settings.offsetTop);
    scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
      if (typeof callback == 'function') { callback.call(this); }
    });
  });
}

You can try to use localStorage to save scroll position. 您可以尝试使用localStorage保存滚动位置。

window.onbeforeunload = function() {
    localStorage.setItem('lastScrollPosition', x);
};
window.onload = function() { scrollTo(localStorage.getItem('lastScrollPosition')); }

rude example 粗鲁的例子

If you want ultimate cross-compatibility, use a simple library that obfuscates the underlying mechanism for storage. 如果要实现最终的交叉兼容性,请使用一个简单的库,该库混淆了底层的存储机制。 This way, regardless of what browser the user has and what technologies that browser implements for storage it works! 这样,无论用户使用哪种浏览器以及该浏览器为存储实现何种技术都可以使用它! LocalStorage is not supported before IE8, but this isn't a problem for consumers it may be for corporate environments. IE8之前不支持LocalStorage,但这对消费者来说不是问题,可能对公司环境而言。

http://www.jstorage.info/ http://www.jstorage.info/

$.jStorage.set(key, value, options);
$.jStorage.set('pageXYZ_scrollTarget', target);

value = $.jStorage.get(key);
value = $.jStorage.get('pageXYZ_scrollTarget');

Alternatively, you can use cookies as they are cross-compatible. 或者,您可以使用cookie,因为它们是相互兼容的。

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

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