簡體   English   中英

HTML5歷史API演示

[英]HTML5 History API Demo

我一直在閱讀關於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能幫助其他人來這個頁面尋找代碼演示。

謝謝。

好的,我為你做了這個例子。 從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,它取決於瀏覽器)來檢索當前狀態。

最后,如果您將整個網址直接輸入到地址欄中,它的工作原理與上面的相同.htaccess;)

我希望這個例子可以幫助你;)

再見

威爾克

PS:有關詳細信息:

  1. 操縱瀏覽器歷史記錄
  2. 歷史對象
  3. 歷史如何

好的,我創建了我認為是簡歷形式的歷史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>

如果它適用於您,請進行Upvote。

請享用!

在這里您可以看到一個簡單的示例HTML5 History API: https//stackoverflow.com/a/9470183/1236238

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM