2013-05-03 21 views
0

我写了一些代码,允许将页面上的一个元素扩展为全屏并将其缩回到原始大小。此代码通过保存页面上其他元素的状态,更改其属性并恢复它们而起作用。这个改变必须在回传后生存,所以我试图使用JSON和隐藏的输入元素来保存状态更改。用JSON保存元素的文档模型

问题中的元素嵌套在多个IFRAME中。因此我必须保存元素所在的文档模型。但是,这会导致JSON转换窒息。我需要一种方法来解决这个问题,可以很容易地转换为JSON并返回。

下面是相关代码:

// e.uniqueID : A unique identifer for the object. 
// e.doc: The document model to which the element belongs (so we can find it later). 
// e.style: The original style of the element. 

function my_preserveElement(gn,elem) 
{ 
    if (elem == null) return; 
    if (elem.style == null) return; 
    if (elem.id == '') elem.id = PseudoGuid.GetNew(); 
    var e = new Object(); 
    e.uniqueID = elem.id; 
    e.doc = elem.document; 
    var cssString; 
    cssString = elem.style.cssText; 
    if(typeof(cssString) != 'string') { cssString = elem.getAttribute('style'); } 
    e.style = cssString; 
    me_aObjectStore[gn][me_aObjectStore[gn].length] = e; 
} 

function my_restoreElements(gn) 
{ 
    for (i = 0; i < me_aObjectStore[gn].length; i++) 
    { 
     var e = me_aObjectStore[gn][i]; 
     var elem = e.doc.getElementById(e.uniqueID); 
     elem.style.cssText = e.style; 
     elem.setAttribute('style',e.style); 
    } 
    me_aObjectStore[gn] = null; 
} 
+0

这个其他线程可能会帮助你弄清楚一些事情:http://stackoverflow.com/questions/1004475/jquery-css-plugin-that-returns-computed-style-of-element-to-pseudo-clone-这-EL/2155757#2155757 – Quickredfox 2013-05-03 15:49:21

回答

0

发现,由于有问题的代码在最里面的框架运行时,我只需要走到框架树,寻找由ID每个元素每个级别。还原功能如下,并且不需要跟踪每个元素的位置(只是其唯一的ID)。

function my_restoreElements(gn) 
{ 
    for (i = 0; i < my_aObjectStore[gn].length; i++) 
    { 
     var e = my_aObjectStore[gn][i]; 

     // Find the element in this window or one of its parents. 
     // Because we need to check the top level frame and w.parent == w.self for that frame, 
     // we use the number of counts to keep the loop from being endless. 
     var w = window; 
     var elem = null; 
     var count = 0; 
     do { 
      elem = w.document.getElementById(e.uniqueID); 
      w = w.parent; 
      count++; 
     } while ((elem == null) && (count < 3)) 
     if (elem != null) { 
      elem.style.cssText = e.style; 
      elem.setAttribute('style',e.style); 
     } 
    } //for 
    my_aObjectStore[gn] = null; 
} 

请注意,我明确地只走三个级别。这是因为在我的具体情况下,这些框架只有几层。其他可以使用此解决方案的应用程序可能需要更深的深度。