我正在尝试保存/恢复回发的滚动位置。我的代码适用于 Firefox 和除 Internet Explorer 之外的所有主要浏览器。
function saveScrollPosition() {
// Save the cookie if the requestor is Internet Explorer
if (navigator.appName.indexOf("Microsoft") != -1) {
alert("Internet Explorer browser has been identified...");
var scrollX, scrollY;
var strA = "KulScrollPos=";
var strB = ",";
var strC = "; path=";
// Depending on the version of Internet Explorer --- call the appropriate API
if (!document.documentElement.scrollLeft)
scrollX = document.body.scrollLeft;
else
scrollX = document.documentElement.scrollLeft;
if (!document.documentElement.scrollTop)
scrollY = document.body.scrollTop;
else
scrollY = document.documentElement.scrollTop;
alert("scrollX = " + scrollX + " and " + "scrollY = " + scrollY);
alert("strA = " + strA);
//document.cookie = "KulScrollPos="+scrollX+","+scrollY+"; path="+document.location.pathname;
document.cookie = strA.concat(scrollX, strB, scrollY, strC, document.location.pathname);
}
// Save the cookie for all other major browsers
else {
document.cookie = "KulScrollPos="+f_scrollLeft()+","+f_scrollTop()+"; path="+document.location.pathname;
}
alert("cookie = " + document.cookie)
}
function restoreScrollPosition() {
alert("Entered the restore method...");
cookieName = "KulScrollPos";
if (document.title == "KFS :: Create Purchase Log") {
resetScrollPosition();
expireCookie( cookieName );
return true;
}
else {
var matchResult = document.cookie.match(new RegExp(cookieName+"=([^;]+);?"));
if ( matchResult ) {
var coords = matchResult[1].split( ',' );
if (coords[1] != 0) {
alert("Restoring the scroll position before scrollTo... " + coords[0] + " and " + coords[1]);
window.scrollTo(coords[0],coords[1]);
parent.window.scrollTo(coords[0],coords[1]);
}
expireCookie( cookieName );
return true;
}
else {
return false;
}
}
请注意我正在打印 cookie 名称的警告框。
Firefox 打印以下内容:
cookie = KulScrollPos=0,1946; kualiSessionId=A7807919-4719-D5B4-91D6-9CC04EEA1BA8;JSESSIONID=1F155C7FC23C48A4DAF557CA4B92D2CB
Internet Explorer 打印以下内容:
cookie = kualiSessionId=072BE31C-6AF5-6D4C-11A4-55E799790C6A; JSESSIONID=76D83E8E7EBA5F25B8A1B1990B9344E8
注意字符串 KulScrollPos=0,1946; 被忽略了 cookie 名称。这只发生在 Internet Explorer 中!
***我尝试了另一种方法来设置我正在设置 document.cookie = ... 的字符串变量(被注释掉的行)。这一行也产生了与上面显示的相同的警报输出。
请注意我的 RestoreScrollPosition 中的 ELSE 块。if (matchResult) 条件总是因此而失败,因此,我在那里调用我的 scrollTo 方法的代码永远不会被调用!
呃,我是不是把字符串连接错了?IE 不喜欢 FF 做什么?
确实非常奇怪的行为!