2013-05-03 20 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; 
} 

請注意,我明確地只走三個級別。這是因爲在我的具體情況下,這些框架只有幾層。其他可以使用此解決方案的應用程序可能需要更深的深度。