【问题标题】:html 5 history restores some changes and not others?html 5 历史恢复了一些更改而不是其他更改?
【发布时间】:2012-11-29 19:58:00
【问题描述】:

我不熟悉使用 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>

当我按下 Show box 时,下面会出现一个红色框,并且 iframe 的内容从 t1.html 变为 t2.html。当我在 chrome 浏览器中按下后退按钮时,iframe 的内容会回到 t1.html ,但红色框并没有消失。

为什么后退按钮会恢复iframe的内容而不是redbox的css样式(返回显示:无);

【问题讨论】:

    标签: javascript html history


    【解决方案1】:

    浏览器的历史只是一个 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

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

    【讨论】:

    • 感谢 Rocket,我在上面的问题描述中将问题加粗。我想这才是我真正感到困惑的问题。
    • 后退和前进按钮只是更改历史记录。历史只是一个 URL 列表。它不包含有关页面的任何信息。您需要自己重新显示红色框。历史只是重新加载 URL。
    • 是的,但是后退按钮怎么会导致 iframe.src 从 t2.html 变为 t1.html?我希望在 onpopstate 中以编程方式执行 mysqlf 操作?
    • 我想是因为iFrame是它自己的页面,所以它正在读取返回按钮并更改页面。我认为您也需要在 iFrame 内的页面中添加一个 onpopstate 事件。
    • 在我的真实代码中,iframe.src 实际上是指向 youtube 视频或 vimeo 视频的链接。我想我不能为这些东西设置 onpopstate 吗?让我有点困惑的是,哪些更改需要以编程方式完成,哪些不需要在 onpopstate 上完成。谢谢f
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2015-01-18
    • 2016-04-16
    • 1970-01-01
    • 2021-07-29
    • 2021-09-03
    • 2017-12-08
    相关资源
    最近更新 更多