在cookie中保存框架集高度并恢复下一个会话

Save frameset heights in a cookie and restore next session

本文关键字:恢复 下一个 会话 高度 cookie 保存 框架      更新时间:2023-09-26

我们有一个框架集(不是iFrames !)应用程序,我们需要保存用户选择的框架的状态。然后在下次点击页面时恢复此状态。

使用jQuery作为首选武器。这就是我们所取得的进展。

 <frameset rows="40,600,40" id="myframeset" name="myframeset">
     <frame name="mytop" id="mytop" src="http://xyz.com/top.html">
     <frameset cols="50%,50%">
        <frame name="leftframe" id="leftframe" src="http://xyz.com">
        <frame name="rightframe" id="rightframe" src="http://xyz.com">
     </frameset>
     <frame name="mybottom" id="mybottom" src="http://xyz.com/bottom.html">
</frameset>

在任何子框架中运行一些jQuery ..(说mybottom)很容易从顶部框架集范围拉行值…

var myrows = $('#myframeset', top.document).attr('rows'); 
   alert(myrows);  // returns 40,600,40

和它很容易改变框架的高度与jQuery .attr太…

$('#myframeset', top.document).attr({'rows':'0,*,300'});
var myrows = $('#myframeset', top.document).attr('rows'); 
   alert(myrows); // returns 0,*,300

但似乎当用户移动帧来改变高度时,手动…它不影响attr的返回值

(手动移动帧,然后点击按钮…)

$("button").click(function() {
  var myrows = $('#myframeset', top.document).attr('rows'); 
    alert(myrows);  //  always returns 0,*,300

我觉得我在这里错过了一个简单的概念…请通知如果有办法,我们可以抓取框架集的值(onUnload),把他们在饼干里…然后在下次用户访问

页面时恢复onload

感谢. .

PS . .如果这不能与行/cols ..也许与窗户的高度/宽度?

完成您的集合(您已经创建了一个函数来调整行):

function getTopRows(){
    var rows = [];
    var main = $("#myframeset", top.document);
    //Get the whole height of the main <frameset>
    var wholeheight = $(main).height();
    //Calculate the relative height of each frame (child) of the main <frameset>
    main.children().each(function(){
         rows.push(Math.round(100*$(this).height()/wholeheight));
    });
    rows = rows.join("%,")+"%"; //Example: 6%,87%,6%
    return rows;
}

调用getTopRows()返回一个相对单元的字符串,可用于设置顶部行。这个值可以通过使用JQuery cookie插件保存:

//You can add this function as an event listener to a button
function saveTopRows(){
    var topRows = getTopRows();
    $.cookie("rows", topRows); //Save data
}
//Execute on load of the page:
(function(){//Anonymous wrapper to prevent leaking variables
    var rows = $.cookie("rows");
    if(rows) $("#myframeset", top.document).attr("rows", rows);
})();

不要忘记添加JQuery cookie插件,要么在源代码中定义它,要么添加一个外部JS文件。参见JQuery网站的Cookie插件的源代码。下载源代码后,将其保存为"jquery.cookie.js",并添加以下代码:

...
<script src="jquery.cookie.js"></script>
<script>
  function getTopRows(){
  //Rest of code

使用jQuery cookie插件,并执行如下操作:

$(window).unload(function() {
   var myrows = // get the stuff you need 
   $.cookie("mycookie", myrows, { expires: 10 }); //expires in ten days
});

然后执行如下操作获取load上的值:

if ($.cookie("mycookie") {         //check if the cookie exists
   myrows = $.cookie("mycookie");  //then get the values
} else {
   //do something else if the cookie does not exist
}

如果attr()不起作用,试试prop()