简体   繁体   English

单击浏览器后退按钮时,将用户带回上一页滚动到的位置

[英]Take User Back to Where They Scrolled to on previous page when clicking Browser Back Button

Is it possible to take a user back to the area of a page where they scrolled down to when pressing the back button in a browser?在浏览器中按下后退按钮时,是否可以将用户带回到他们向下滚动到的页面区域? As in --- pageA is double your screen size (hence you have to scroll to read more).如 --- pageA 是您屏幕尺寸的两倍(因此您必须滚动以阅读更多信息)。 You click a link on pageA to go to a new page - pageB.您单击页面 A 上的链接转到新页面 - 页面 B。 After reading you click back in browser.阅读后,您在浏览器中单击返回。 Now when you return to pageA you are back at the top and have to scroll down to where you were to continue reading the rest of the page.现在,当您返回 pageA 时,您又回到了顶部,必须向下滚动到您要继续阅读页面其余部分的位置。

Is there a Jquery or JS way to return to that point in the page.是否有 Jquery 或 JS 方式返回到页面中的那个点。 Maybe something with .scrollTop()?也许有 .scrollTop() 的东西?

If the content is loaded after page "load" event firing, then the back button would not take you back to the position you were.如果在页面“加载”事件触发后加载内容,则后退按钮不会将您带回原来的位置。 Because the browser scrolls before the 'load' event.因为浏览器在 'load' 事件之前滚动。

To make the browser remember the scroll position in this case, you have to store the scroll position and status (what content have been loaded) somewhere before navigating away.在这种情况下,为了让浏览器记住滚动位置,您必须在导航离开之前将滚动位置和状态(已加载的内容)存储在某处。 Either in the cookie, or in the url hash.无论是在 cookie 中,还是在 url 哈希中。

If pageA is just a static page without dynamic content (loaded after 'load' event, the browser should remember the scroll position when you go back.如果 pageA 只是一个没有动态内容的静态页面(在 'load' 事件之后加载,浏览器应该在你返回时记住滚动位置。

For dynamic content, there at least includes two parts.对于动态内容,至少包括两部分。 One is recovering the page status when click "Back" button, so all the dynamic content is loaded, some expander are expanded or collapsed.一种是在单击“返回”按钮时恢复页面状态,因此所有动态内容都被加载,一些扩展器被展开或折叠。 The other is scroll to there.另一个是滚动到那里。

The first part depends on how the page is implemented.第一部分取决于页面的实现方式。 The 2nd part you can put the scroll top into the cookie when page doing onUnload.第二部分您可以在页面执行 onUnload 时将滚动顶部放入 cookie。 For example例如

$(window).unload(function() {$.cookie('scrollTop',$(window).scrollTop());});

You can do this by using session storage.您可以通过使用会话存储来做到这一点。

$(window).scroll(function () {
  //set scroll position in session storage
  sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
   //return scroll position in session storage
   $(window).scrollTop(sessionStorage.scrollPos || 0)
};
window.onload = init;

You can use the following code to detect the scroll position.您可以使用以下代码来检测滚动位置。

 $(window).scroll(function (event){
    var scroll = $(window).scrollTop();
    // Do something
 });

Then store scroll in a session and when you click back do scrollTop(scroll) .然后将滚动存储在会话中,当您单击返回时执行scrollTop(scroll)

This should definitely be done using the History API since it is the only way of knowing for sure that the user went back to the page using the back button of the browser.这绝对应该使用History API来完成,因为这是确定用户使用浏览器的后退按钮返回页面的唯一方法。

First of all, you want to prevent the default scroll restoration of the browser in order to handle it yourself.首先,您要阻止浏览器的默认滚动恢复,以便您自己处理。 See this article for details.有关详细信息,请参阅此文章

if ('scrollRestoration' in history) history.scrollRestoration = 'manual'

Then you need to store the scroll position in the history.state when the user leaves the page.然后你需要在用户离开页面时将滚动位置存储在history.state This can be done on beforeunload using history.replaceState .这可以在beforeunload 上使用history.replaceState 完成

window.addEventListener('beforeunload', storeScrollPositionInHistoryState)
function storeScrollPositionInHistoryState() {
  // Make sure to add lastScrollPosition to the current state
  // to avoid removing other properties
  const newState = { ...history.state, lastScrollPosition: scrollY }

  // Pass the current location.href since you only want to update
  // the state, not the url
  history.replaceState(newState, '', location.href)
}

or with ES5或使用 ES5

function storeScrollPositionInHistoryState() {
  var newState = Object.assign({}, history.state, { lastScrollPosition: scrollY })
  history.replaceState(newState, '', location.href)
}

Finally, whenever your page is ready to scroll back to its previous position, you check if history.state.lastScrollPosition is defined and if it is the case, you restore the scroll position and remove it from the history.state .最后,每当您的页面准备好滚动回之前的位置时,您检查是否定义了history.state.lastScrollPosition ,如果是,则恢复滚动位置并将其从history.state删除。

function restoreLastScrollPositionIfAny() {
  if (typeof history.state.lastScrollPosition !== 'number') return

  scrollTo(scrollX, history.state.lastScrollPosition)
  const cleanState = { ...history.state }
  delete cleanState.lastScrollPosition
  history.replaceState(cleanState, '', location.href)
}

There are still one edge case that is not covered:还有一种边缘情况没有被涵盖:

  • The user might have resized the window after leaving the page which can result in an incorrect scroll position when going back to the page.用户可能在离开页面后调整了窗口大小,这可能导致返回页面时滚动位置不正确。 Developers resize the window very often, but real users not that much.开发人员经常调整窗口大小,但真正的用户并没有那么多。 That's why I consider it as an edge case.这就是为什么我认为它是一种边缘情况。

One way to solve it could be to also store the window size in the history.state and avoid restoring the scroll position if the current window size doesn't match the one stored in the state.解决它的一种方法可能是将窗口大小也存储在history.state ,如果当前窗口大小与存储在状态中的窗口大小不匹配,则避免恢复滚动位置。

Hope it helps.希望能帮助到你。

After trying @bowen option I have arrived to a better one with smooth scroll and without the problem said by @Frits在尝试了@bowen 选项后,我找到了一个更好的选项,滚动顺畅并且没有@Frits 所说的问题

      $(window).scroll(function () {
        //set scroll position in session storage
        if ($(window).scrollTop() > 500)
          sessionStorage.scrollPos = $(window).scrollTop();
      });

      var init = setTimeout(function(){
         //return scroll position in session storage
         if (sessionStorage.scrollPos > 500){
            $("html").animate({ scrollTop: sessionStorage.scrollPos },2000);
          }
        },1000);
      window.onload = init;
  //For Angular
  //Save your scroll position once you scroll
  @HostListener('window:scroll', ['$event']) onScrollEvent($event){
    sessionStorage.scrollPos = window.scrollY
  } 

  //Scroll to the save value postion
  ngAfterViewInit(){
    window.scrollTo(0, sessionStorage.scrollPos)
  }
<button onclick="goBack()">Go Back</button>

<script>
function goBack() {
  window.history.back();
}
</script>

This will work same as the back button on browser这将与浏览器上的后退按钮相同

暂无
暂无

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

相关问题 如何通过在javascript中单击浏览器的后退按钮将页面恢复到之前的状态 - How to take back a page to its previous state by clicking the back button of the browser in javascript 单击浏览器的“后退”按钮时,返回上一页的上一个位置 - Go Back to the Previous Location on Previous Page when Clicking Browser Back Button 单击后退按钮时是否强制浏览器将用户带到页面的顶部? - Force the browser to take user to the TOP of the page when the back button is clicked? 不允许将CSS携带到上一页(单击浏览器后退按钮后) - Not allowing CSS to be carried to previous page (after clicking browser back button) 当我单击浏览器的“后退”按钮时,它应该转到同一页面的上一个活动 - when I clicking on Back button of browser , it should go to the previous activity of the same page 当用户返回原始页面时,在浏览器中检测到后退按钮 - Detect back button in browser when the user go back to original page 通过单击后退按钮重新加载上一页 - Reload the previous page by clicking the back button 单击浏览器的后退按钮时重定向到特定页面 - redirecting to a specific page when clicking browser's back button 付款后在浏览器中单击后退按钮可返回到其他页面 - Return to different page when clicking back button in browser after payment 单击浏览器上的后退按钮时如何加载确切的页面? - How to load the exact page when clicking back button on browser?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM