Javascript HTML5历史记录恢复一些更改,而不是其他更改?

Javascript HTML5历史记录恢复一些更改,而不是其他更改?,javascript,html,history,Javascript,Html,History,我不熟悉使用HTML5历史对象。我尝试了以下代码: <!DOCTYPE html> <html> <head> <script type="text/javascript"> history.pushState({somethinggoeshere:'but what?'}, 'Does a title go here?', '?begin=true'); window.addEventLis

我不熟悉使用HTML5历史对象。我尝试了以下代码:

<!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>

pushState({somethingGoesher:'但是什么?'},'标题在这里吗?','begin=true');
window.addEventListener('popstate',函数(事件){
log('popstate fired!');
console.log(event.state);
});
函数dosomething()
{
document.getElementById('box').style.display='block';
document.getElementById('iframe').src='t2.html';
pushState({somethingGoesher:'but what?'},'title在这里吗?','complete=true');
}
展示箱
当我按下ShowBox时,下面会出现一个红色框,iframe的内容从t1.html变为t2.html。当我在chrome浏览器中按下back按钮时,iframe的内容会返回到t1.html,但红色框不会消失


为什么“返回”按钮恢复iframe的内容,但不恢复红框的css样式(返回显示:无)

浏览器的历史记录只是一个URL列表
pushState
允许您将对象与历史记录中的URL相关联,如果您愿意,则为“状态”。此对象是传递给
pushState
的第一个参数

就像“正常”浏览历史记录一样,页面的实际状态不会被保存。这取决于你。在您的对象中,您应该保存应该显示的红色框,并在
onpopstate
中再次显示它

例如:

history.pushState({
    redBox: document.getElementById('box').style.display
}, 'Most browsers ignore this parameter.', '?complete=true');
然后在
onpopstate
中,将
document.getElementById('box').style.display
设置为
event.state.redBox


编辑:iFrame就像一个新的浏览器窗口,因此它有自己的历史对象。当您单击“后退”时,iFrame会看到这一点并返回历史。您需要有
window.addEventListener('popstate',function()
也在iFrame的页面内。

谢谢Rocket,我在上面的问题描述中加粗了这个问题。我想这才是我真正困惑的问题。后退和前进按钮只是更改了历史记录。历史记录只是一个URL列表。它不包含任何关于页面的信息。你需要自己重新显示红色框。历史记录只是重新加载URL。是的,但是为什么返回按钮会导致iframe.src从t2.html更改为t1.html?我本来希望在onpopstate中以编程方式执行mysqlf?我认为这是因为iframe是它自己的页面,所以它正在读取返回按钮并更改页面。我认为您需要添加一个
onpopstate
在我的真实代码中,iFrame.src实际上是一个指向youtube视频或vimeo视频的链接。我想我不能为这些东西设置一个onpopstate?这让我有点困惑,哪些更改需要通过编程来完成,哪些不需要在onpopstate上。谢谢