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

时间:2011-10-06 21:09:51

标签: javascript jquery frames

我们有一个框架集(不是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)放置它们 在一个cookie ..然后下次用户来到页面时恢复onload

非常感谢..

PS ..如果这不能用行/列来完成..也许窗口高度/宽度?

2 个答案:

答案 0 :(得分:1)

使用jQuery cookie plugin,并执行以下操作:

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

然后执行类似的操作以获取加载值:

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()

答案 1 :(得分:1)

完成你的收藏(你已经创建了一个调整行的功能):

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文件。有关Cookie插件的来源,请参阅JQuery网站。下载源代码后,将其另存为“jquery.cookie.js”,并添加以下代码:

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