javascript滚动到新页面上的位置

标签 javascript jquery

我有一个简单的 javascript,我正在尝试让它工作,但是

我能够使用

收集 y 轴

var tempScrollTop = $(window).scrollTop();

但我无法滚动到刷新后的网址中的同一位置。

因为没有错误显示我无法弄清楚是什么导致我的脚本无法工作。

$(".refreshfix").click(function(e){
  event.preventDefault();

  var tempScrollTop = $(window).scrollTop();
  var address = $(this).attr("sorttype");

  // window.location.replace(address);
  // window.location.href = address;
  // window.location = address;
  // document.location.reload(true)
  window.location.assign(address);

  $(window).scrollTop(tempScrollTop);
  // window.scrollTo(0, tempScrollTop);
  console.log(tempScrollTop)

});

我尝试了使用scrollTo和scrollTop的变体。我注释掉了一些我尝试过但不起作用的代码。

我最好的猜测是,它移动到的这个新页面没有丢失变量“tempScrollTop”,但我不知道如何传输要在下一页中使用的变量。我在 stackoverflow 上找到了一些引用,这些引用允许我滚动到特定位置,但没有提供有关滚动到刷新页面上的位置的任何提示。我是 JavaScript 新手,有人对此有什么想法吗?

谢谢

最佳答案

当页面刷新时,由于window.location.assign(),所有变量都消失得无影无踪。加载新页面。

但是你可以使用localStorage()存储/检索值。这又快又简单。

// On load, get the value if exist
var scroll_y = parseInt( localStorage.getItem("scroll_y") );

// If there is a value, scroll!
if(!isNaN(scroll_y)){
  $(window).scrollTop(scroll_y);
  console.log(scroll_y);
}

// On click, store the value.
$(".refreshfix").click(function(e){
  event.preventDefault();

  var tempScrollTop = $(window).scrollTop();
  var address = $(this).attr("sorttype");

  localStorage.setItem("scroll_y",tempScrollTop);
  window.location.assign(address);
});

关于javascript滚动到新页面上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48220199/

相关文章:

javascript - 将多个文档数组展开为新文档

javascript - Android WebView 在底部添加奇怪的空白区域

javascript - HighCharts 日期格式没有微秒 (%f)

javascript - .parent().toggleClass 不工作

javascript - 从 JavaScript.push 方法显示工具提示

Javascript:如何使用 event.target 定位一个称为 Margin 的外部 div?

javascript - 单选按钮间隙

javascript - 使用 jquery 将字符串转换为 UTC 时间

jquery - 为 jQuery 模板中的每个 block 生成唯一的 id

javascript - 在窗口大小调整到低于特定窗口大小时运行函数