简体   繁体   English

在页面刷新时重置滚动位置,在现代浏览器上不起作用

[英]Reset scroll position on page refresh, did't work on modern browsers

I'm trying to reset browser scroll position on refresh and apparently it didn't work or ain't possible with modern browsers, am I wrong? 我正在尝试在刷新时重置浏览器滚动位置,但显然这在现代浏览器中不起作用或无法实现,对吗?

The code: 编码:

$(window).on('beforeunload', function() {
$('html, body').scrollTop($('#scroll-to-div-id-anchor').offset().top); });

Maybe I'm handling this incorrectly and there is another way to achieve that? 也许我处理不正确,还有另一种方法可以实现?

I tried all variations and possible options to this code, but it didn't work on Safari and Chrome (both on desktop and, especially - mobile). 我尝试了此代码的所有变体和可能的选项,但是在Safari和Chrome(无论是台式机还是移动设备)上均无法使用。

If you want the page to move to a certain element on reload, the expected behavior is to move the page to that point once it has been loaded. 如果您希望页面在重新加载时移至某个元素,则预期的行为是在页面加载后将其移至该点。 If you tried to move the page before it has been loaded, you won't know where you have to scroll to and if you tried to move it on unload, it's not guaranteed that that point will be saved once it's reloaded. 如果您试图在页面加载之前将其移动,则将不知道必须滚动到的页面;如果您试图在卸载页面时将其移动,则不能保证该点在重新加载后将被保存。

You can probably save the scroll location to the localStorage on unload and attempt to load the location onload, but in this case I would recommend just moving the page onload. 您可能可以在卸载时将滚动位置保存到localStorage并尝试在位置加载时加载位置,但是在这种情况下,我建议您仅在页面加载时移动。

 $(document).ready(function() { $('html, body').scrollTop($('#scroll-to-div-id-anchor').offset().top); }); 

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

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