我有一个简单的 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/