AngularJs浏览器“后退"按钮:返回页面上的上一个位置 [英] AngularJs Browser Back Button: Go Back to Previous Spot on Page

查看:587
本文介绍了AngularJs浏览器“后退"按钮:返回页面上的上一个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular用于单页应用程序.有时我的物品清单较长.当用户向下滚动页面并单击该项目时,他们将转到该项目的详细视图.如果他们在浏览器上单击了后退"按钮,Angular会将其返回到列表,但它会返回到列表的顶部.

I'm using Angular for a single page application. Sometimes I have a longer list of items. When the user scrolls down the page and clicks on the item, they go to a detailed view for that item. If they hit the back button on the browser angular takes them back to the list, but it goes back to the top of the list.

通常在简单的HTML页面上,如果您向下滚动页面,然后单击链接并转到另一个页面(如果您在浏览器中单击后退"按钮),它将带您直接回到您所在的滚动位置该页面.如果您要查看项目列表,这将非常有帮助.

Normally on a simple HTML page, if you scroll down a page, and click on a link and go to another page if you hit the back button on the browser, it takes you right back to the scroll location where you were on that page. This is very helpful if you're going through a list of items.

是否有一种方法可以使Angular模仿该行为,以便使用后退"按钮将用户带回到列表和相同的滚动位置?

Is there a way to have Angular mimic that behavior so that using the back button will take the user back to the list and the same scroll location?

推荐答案

听起来您想使用HTML历史记录API,例如window.history.pushState()window.history.popState().听起来您也想使用浏览器滚动.

It sounds like you want to make use of the HTML history API such as window.history.pushState() and window.history.popState(). It also sounds like you want to use browser scrolling.

一个快速的Google搜索发现我有关$ location的文档有关AngularJS文档的滚动文档.

A quick google search found me this documentation about $location and this documentation about scrolling from the AngularJS docs.

我不知道如何在AngularJS中执行此操作,但是在jQuery中,您可以使用pushState()将特定的url添加到浏览器历史记录中(在同一页面上可能是#),然后可以添加一个popState()处理程序,当用户单击后退"按钮时,除了刷新页面外,还可以执行其他操作.

I don't know how to do this in AngularJS, but in jQuery you can use pushState() to add a specific url to the browser history (that might be a # on your same page) and then you can add a popState() handler that will do something other than refresh the page when the user clicks the back button.

例如

$(document).on('load',function(){
 window.history.replaceState({element: {positionY: 0}},"load",location.pathname);
});

$(mylink).click(function(evt){
 // something like: window.history.pushState(evt.target);
});

// this occurs when the user clicks the back button
$(document).on("popstate", function(evt) {
 evt.preventDefault(); // prevents page refresh
 var state = evt.originalEvent.state;
 window.scrollTo(0,state.element.positionY);
}

这篇关于AngularJs浏览器“后退"按钮:返回页面上的上一个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆