HTML5历史API演示(HTML5 History API Demo)

2019-06-24 09:36发布

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

这里是一个工作的jsfiddle :4个按键和4个格。 当用户按下一个按钮,它示出了相应的面板。

什么我希望做的是:

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帮助别人谁就会来到这个网页,寻找代码演示。

谢谢。

Answer 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菜单,链接,说明,行动,数据,historyState,采取行动;

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,它依赖于浏览器)来检索当前状态。

而且,在最后,如果你直接输入完整的网址到地址栏,它的工作原理与上面的.htaccess相同;)

我希望这个例子可以帮助你;)

再见

威尔克

PS:欲知详情:

  1. 操纵浏览器历史记录
  2. 历史对象
  3. 历史HOWTO


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

给予好评,如果你的作品。

请享用!



Answer 3:

在这里你可以看到一个简单的例子,HTML5历史API: https://stackoverflow.com/a/9470183/1236238



文章来源: HTML5 History API Demo