【问题标题】:HTML5 History API DemoHTML5 历史 API 演示
【发布时间】:2012-05-21 06:04:11
【问题描述】:

我一直在阅读有关 HTML5 历史 API 的内容,但到目前为止,我还没有找到一个简单的工作演示来展示代码机制。

这是一个有效的jsfiddle:4 个按钮和 4 个 div。当用户按下一个按钮时,它会显示相应的面板。

我想做的是:

1) rewrite the URL so that when the user is on panel 4 the url ends with /Panel4
2) make the back button and forward button work with the history API.

我知道有 history.js 插件,但我想了解 API 如何以最简单的形式工作。

希望 jsfiddle 能帮助到此页面寻找代码演示的其他人。

谢谢。

【问题讨论】:

标签: javascript html html5-history


【解决方案1】:

好的,我为你做了这个例子。 从 HTML 代码开始(index.html):

<!DOCTYPE html>
<html>
    <head>
        <title>Stackoverflow</title>
        <script type="text/javascript" src="sof.js"> </script>
    </head>
    <body onLoad="load();">
        <ul id="menu">
            <li><a href="/home">home</a></li>
            <li><a href="/about">about</a></li>
            <li><a href="/blog">blog</a></li>
            <li><a href="/photos">photos</a></li>
        </ul>
        <button onclick="back ();">Back</button>
        <button onclick="ff ();">Forward</button>
        <div>
            Action: <span id="action"></span><br/>
            Url: <span id="url"></span><br/>
            Description: <span id="description"></span>
        </div>
    </body>
</html>

然后是javascript文件(sof.js):

var menu, url, description, action, data, historyState, act;

function $ (id) {return document.getElementById (id);}

// Updates infos
function update (state) {
    action.innerHTML = act;
    url.innerHTML = state.url;
    description.innerHTML = state.description;
}

// Goes back
function back () {
    act = 'Back';
    history.back ();
}

// Goes forward
function ff () {
    act = 'Forward';
    history.forward ();
}

function load () {
    menu = $ ('menu');
    url = $ ('url');
    description = $ ('description');
    action = $ ('action');

    // State to save
    historyState = {
        home: {
            description: 'Homepage'
        } ,
        about: {
            description: 'Infos about this website'
        } ,
        blog: {
            description: 'My personal blog'
        } ,
        photos: {
            description: 'View my photos'
        }
    };

    // This is fired when history.back or history.forward is called
    window.addEventListener ('popstate', function (event) {
        var hs = history.state;

        if ((hs === null) || (hs === undefined)) hs = event.state;
        if ((hs === null) || (hs === undefined)) hs = window.event.state;

        if (hs !== null) update (hs);
    });

    menu.addEventListener ('click', function (event) {
        var el = event.target;
        // Prevents url reload
        event.preventDefault ();

        // Handles anchors only
        if (el.nodeName === 'A') {
            // Gets url of the page
            historyState[el.innerHTML].url = el.getAttribute ('href');
            // Creates a new history instance and it saves state on it
            history.pushState (historyState[el.innerHTML], null, el.href);
            act = 'Normal navigation';
            update (historyState[el.innerHTML]);
        }
    });

    // Handles first visit navigation
    var index = location.pathname.split ('/');
    index = index[index.length-1];
    if (index !== '') {
        historyState[index].url = location.pathname;
        history.pushState (historyState[index], null, location.pathname);
        act = 'First visit';
        update (historyState[index]);
    }
}

还有一个 .htaccess 用于直接请求:

RewriteEngine On

RewriteRule ^home$ ./index.html
RewriteRule ^about$ ./index.html
RewriteRule ^blog$ ./index.html
RewriteRule ^photos$ ./index.htm

每次单击锚点时,都会将一个新的历史实例推送到历史堆栈中,并与它一起保存一个对象(称为状态):本地 url 更改但加载被“event.preventDefault()”停止方法。 此外,更新了一些信息(如 URL、描述和操作)。

然后,使用“后退”和“前进”按钮,您可以浏览历史并使用“history.state”(或 event.state 或 window.event.state,取决于浏览器)检索当前状态.

最后,如果你直接在地址栏中输入整个 url,它的工作原理与上面的 .htaccess 相同;)

我希望这个例子对你有帮助;)

威尔

PS:更多详情:

  1. Manipulating the browser history
  2. History object
  3. History howto

【讨论】:

  • 我认为 jsFiddle 存在一些问题,因为当我单击锚点时,页面已加载,但如果不应该...我建议您尝试进入本地主机,创建 index.html和 web 服务器根目录中的 sof.js 文件;)它适用于我:D
【解决方案2】:

好的,我创建了我认为最简单的历史 API 演示形式。

它不能在 jsfiddle 中运行,因为它需要在自己的窗口中运行。但是,如果您将代码复制粘贴到记事本中,在指示的地方添加对 jquery 的引用,并将其作为 html 文件保存在桌面上,它将起作用。当然,它在 IE 中不起作用,但我们都知道。 我提供了两个版本:一个没有 URL 重写组件(它可以在您的桌面上工作),我还注释掉了您可以操作 URL 的版本。对于后者,您需要从远程或本地服务器运行它。

我一直在努力让它在所有浏览器上运行,因为 Chrome、Safari 和 Firefox 的工作方式不同!代码如下:

    <html>
    <head>
    <style type="text/css">

    .Panel{
       width:200px;
       height:100px;
       background:red;
       display:none;
       color:white;
       padding:20px 20px;}

    .ChangeButton{
       margin:10px 10px;
       float:left;}   

    </style>

   // add reference to jquery.js file here 
   // <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>        

    <script type="text/javascript">

    var TheURL; // if you don't need URL rewrite, then we're always going to 
                // show the same URL. Remove this line if you want URL rewrite.

    var MyDivs = { // this object stores the name and the URL of each possible state
       ShowPanel1: {panelID:'Panel1', DisplayURL:'/panel1'},
       ShowPanel2: {panelID:'Panel2', DisplayURL:'/panel2'},
       ShowPanel3: {panelID:'Panel3', DisplayURL:'/panel3'},
       ShowPanel4: {panelID:'Panel4', DisplayURL:'/panel4'},
    };

    $(document).ready(function () {

    TheURL = document.URL; // You can remove this line if you're doing
                           // URL rewrite

    window.addEventListener('popstate', function (event) {

       //cross-browser nightmare here!!!!!
       var HistoryState = history.state;

       if (HistoryState === null || HistoryState === undefined) {
            HistoryState = event.state; }

       if (HistoryState === null || HistoryState === undefined) {
            HistoryState = window.event.state; }

       SwitchPanel(HistoryState);
    });

    $('.ChangeButton').click(function () {
           DoChange(parseInt($(this).attr('id').charAt(6), 10)); });

    DoChange(1);

    });

    function DoChange(ButtonID) {

       switch (ButtonID) {

       // here's the 2-version option: 
       // toggle the commented and uncommented history.pushState
       // lines to see the change to the URL in action
       case 1:
           SwitchPanel(MyDivs.ShowPanel1.panelID);
           history.pushState(MyDivs.ShowPanel1.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel1.panelID, "", MyDivs.ShowPanel1.DisplayURL);
           break;
       case 2:
           SwitchPanel(MyDivs.ShowPanel2.panelID);
           history.pushState(MyDivs.ShowPanel2.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel2.panelID, "", MyDivs.ShowPanel2.DisplayURL);
           break;
       case 3:
           SwitchPanel(MyDivs.ShowPanel3.panelID);
           history.pushState(MyDivs.ShowPanel3.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel3.panelID, "", MyDivs.ShowPanel3.DisplayURL);
           break;
       case 4:
           SwitchPanel(MyDivs.ShowPanel4.panelID);
           history.pushState(MyDivs.ShowPanel4.panelID, "", TheURL);
           // history.pushState(MyDivs.ShowPanel4.panelID, "", MyDivs.ShowPanel4.DisplayURL);
           break;
       }
    }

    function SwitchPanel(PanelID) {

       if (PanelID === null) {return false;}

       $('.Panel').hide();
       $('#' + PanelID).fadeIn('medium');
    }

    </script>
    </head>

    <body>

    <input type="button" id="Button1" class="ChangeButton" value="panel 1" />
    <input type="button" id="Button2" class="ChangeButton" value="panel 2" />
    <input type="button" id="Button3" class="ChangeButton" value="panel 3" />
    <input type="button" id="Button4" class="ChangeButton" value="panel 4" />

    <div id="PanelContainer" style="clear:both;">

       <div class="Panel" id="Panel1">panel 1</div>
       <div class="Panel" id="Panel2">panel 2</div>
       <div class="Panel" id="Panel3">panel 3</div>
       <div class="Panel" id="Panel4">panel 4</div>

    </div>

    </body>
    </html>

如果它对您有用,请点赞。

享受吧!

【讨论】:

  • 有趣的是如何使用 popstate 事件让它在任何浏览器上运行;)但是,在您的示例中,没有您要求的 url 导航。
  • @Wilk:好的,我添加了 URL 更新功能;我决定不对我的应用使用 URL 重写。当然,它在 IE 中不起作用,但我不是在寻找它,只是我可以放在我的网站上的一些简单的东西。对于 IE,我只是告诉用户点击“返回”将注销他们并显示取消或继续消息。我的应用将在 10 月启动,届时 IE10 应该已经启动。
  • 非常感谢!我刚刚根据您的建议编辑了我的解决方案:D 现在它在 Chrome 上也可以正常工作;)
猜你喜欢
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 2023-03-19
  • 2018-03-07
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多