2

我正在编写一个使用 HTML5 推送状态(回退到哈希标签)来处理客户端导航的单页 Web 应用程序。

我注意到的一件事是,如果用户向下滚动页面然后单击指向另一个页面的链接,当他们导航到该页面时,浏览器仍将保持在滚动位置。

我想要的是,如果您转到新页面,它会平滑地将您滚动到顶部(与所有网站在跟随链接时的行为相同)。

我在我的导航控制器中通过一个小 jquery 动画实现了这一点,我现在遇到的问题是,如果您单击浏览器后退按钮,您将不会最终处于您之前所在的滚动位置,而是您将在上一页但是您将被滚动到顶部。

是否可以检测上一个/当前客户端导航是否是由浏览器的后退或前进按钮引起的?如果是这样,我将使用它来防止滚动。

干杯

4

2 回答 2

0

据我所知,您只能区分“我的应用程序更改了主题标签”与“浏览器强制更改主题标签”之间的区别。

这就是我检查它的方式:

当您的控制器使用其新标签推送新状态(打开页面)时,请在将其设置为 window.location.hash 之前将此新标签存储在全局 javascript 变量中。当您捕捉到“hashchange”事件时,您会将您的这个全局变量与 window.location.hash 进行比较。如果全局变量与新的哈希标记相同,则意味着您的应用程序只是更改了哈希本身(并打开了新页面)。如果未设置全局变量,则表示浏览器强制导航。但是,您无法知道浏览器是因为地址栏编辑还是因为后退/前进按钮而强制导航。

考虑这段代码:

// Global hashtag variable, used to compare state changes
var gCurrentHash = window.location.hash;

// Called when hashtag is changed by the browser
function onHashChange(event)
{
    var hash_tag = window.location.hash;

    if (hash_tag != gCurrentHash)
    {
        // Browser forced navigation
    }
    else
    {
        // App caused navigation
    }
}

window.addEventListener('hashchange', onHashChange, false);

在您的控制器中,在您更新哈希标记之前,调用以下代码:

gCurrentHash = window.location.hash;

在您实际更改 window.location.hashtag 之前调用它非常重要!

[编辑] 您可以尝试这种替代方法:将主题标签更改的历史记录存储在 cookie 中并比较更改。根据该信息,您可以估计后退/前进导航事件。

于 2011-11-30T13:08:47.830 回答
0

我希望我目前正在开发的网站能够以相同的方式响应,无论用户是否输入了特殊的 ajax 识别哈希标签、为其添加书签或单击相应的页面链接。因此,我会查看主题标签本身的模式,并在需要时强制导航。

例如:

var myDefaultPageName = "myAjaxPage1";

// hash tags in this domain may indicate ajax page navigation
// using '#!' to indicate ajax links however, allowing user to type in 
// hashtag without '!' so function understands both '#!myAjaxPage1' and
// '#myAjaxPage1' as ajax requests, the pattern of the hashtag will be
// checked to determine if ajax navigation is needed

function processHashtagChange() {
    // note: bookmarked urls may be #! or #, need to understand both
    var startIndex = 1; // skip '#'
    if (location.hash.charAt(1) == '!') { // check for special '#!' ajax prefix
        startIndex++;
    }

    // extract ajax pagename from hash
    var pagename = location.hash.substring(startIndex); 

    var regex = "."; // match everything for now, hash tags 
                     // only used for ajax navigation here

    if (pagename.length == 0) // default to something if needed, allows 
    {                         // back button to http://mydomain.com to load 
                              // default ajax page
        pagename = myDefaultPageName;
    }

    if (pagename.match(regex)) { // does this hash indicate ajax navigation
        var pageurl = '/?page=' + pagename;    
        loadPageViaAjax(pageurl); // update the dom via ajax
    }
}
于 2011-12-14T01:16:40.787 回答