2012-11-29 29 views
3

我是使用html 5歷史對象的新手。我嘗試下面的代碼:html 5歷史恢復一些變化,而不是別人?

<!DOCTYPE html> 
<html> 
     <head> 
       <script type="text/javascript"> 

    history.pushState({somethinggoeshere:'but what?'}, 'Does a title go here?', '?begin=true'); 
window.addEventListener('popstate', function(event) { 
    console.log('popstate fired!'); 
    console.log(event.state); 

}); 

function dosomething() 
{ 
    document.getElementById('box').style.display = 'block'; 
    document.getElementById('iframe').src = 't2.html'; 
    history.pushState({somethinggoeshere:'but what?'}, 'Does a title go here?', '?complete=true'); 
} 

       </script> 
     </head> 
     <body> 
       <a onclick="dosomething();">Show box</a> 
       <div id="box" style="background:red; height:100px; display:none;"></div> 
       <iframe id="iframe" src="t1.html"></iframe> 
     </body> 
</html> 

當我按下顯示框,下方會出現一個紅色的框,和iframe的內容從t1.html去t2.html。當我在Chrome瀏覽器中按下後退按鈕時,iframe的內容會返回到t1.html,但紅色框不會消失。

爲什麼後退按鈕恢復IFRAME而不是CSS樣式的紅盒子的內容(回顯示:無);

回答

3

瀏覽器的歷史記錄只是一個URL列表。 pushState可讓您將對象與歷史記錄中的網址相關聯,如果您願意的話,可以使用「狀態」。該對象是傳遞給pushState的第一個參數。

就像瀏覽「正常」歷史時一樣,實際頁面的狀態不會被保存。這取決於你。在你的對象中,你應該保存紅色方框,並在onpopstate再次顯示。

如:

history.pushState({ 
    redBox: document.getElementById('box').style.display 
}, 'Most browsers ignore this parameter.', '?complete=true'); 

然後在onpopstate,設置document.getElementById('box').style.displayevent.state.redBox

編輯:iFrame就像一個新的瀏覽器窗口,所以它有它自己的歷史對象。當你點擊「返回」時,iFrame會看到並返回歷史。您也需要在iFrame頁面內部有window.addEventListener('popstate', function()

+0

謝謝Rocket,我在上面的問題描述中加粗了問題。我想這是我困惑的真正問題。 – John

+0

後退和前進按鈕只是更改歷史記錄。歷史只是一個URL列表。它不包含有關該頁面的任何信息。您需要自己重新顯示紅色框。歷史記錄只是重新加載網址。 –

+0

是的,但後退按鈕如何導致iframe.src從t2.html更改爲t1.html?我期待在onpopstate中以編程方式執行mysqlf? – John