2012-05-13 12 views
2

私はHTML5履歴APIについて読んできましたが、これまでのところ、コードを使ってメカニックを示す簡単なデモが見つかりませんでした。HTML5履歴APIデモ

ここには、jsfiddle:4つのボタンと4つのdivがあります。ユーザーがボタンを押すと、対応するパネルが表示されます。私はしているよ何

されています。私は、history.jsプラグインがあります知っているが、私はAPIは、その最も単純な形でどのように機能するかを理解したい

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. 

jsfiddleは、コードデモを探してこのページに来る他の人を助けてくれることを願っています。

ありがとうございました。

+0

これはあなたを助けることができるhttps://github.com/remy/html5demos/blob/652fd1c914a475d0d5e96b76d81db383190806c0/demos/history.htmlは – Wilk

+0

我々はすでに持っていますHTML5履歴APIをカバーするタグを追加しないでください。 – Charles

答えて

2

を[OK]を、私は歴史のAPIのデモの最も単純な形式だと思うものを作成しました。

独自のウィンドウで実行する必要があるため、jsfiddleでは動作しません。ただし、メモ帳にコードをコピーして貼り付け、jqueryへの参照を追加し、htmlファイルとしてデスクトップに保存するとうまくいきます。もちろん、IEでは動作しませんが、私たちは皆それを知っています。 私は2つのバージョンを入れました: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> 

アップヴォートはあなたのために機能します。

お楽しみください! http://html5demos.com/history そして、これはあまりにも::

+0

どのブラウザでもポップステートイベントを使ってどのように動作させるか興味深い;)しかし、あなたの例では、要求した通りのURLナビゲーションはありません。 – Wilk

+0

@Wilk:ok、URL更新機能を追加しました。私は自分のアプリにURLリライトを使わないことにしました。もちろん、IEでは動作しませんが、私はそれを探していませんでした。私は自分のサイトに置くことができる単純なものです。 IEの場合、私はちょうど "戻る"を打つとキャンセルまたは進行メッセージでそれらをログアウトすることをユーザーに伝えます。私のアプリは10月に起動し、その後IE10が立ち上げられるはずです。 – frenchie

+0

多くのありがとう!私はちょうどあなたの提案で私の解決策を編集しました:D今はChromeでもうまくいきます;) – Wilk

3

私はこの例を作成しました。 (sof.js

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

そしてジャバスクリプトファイル:HTMLコード(index.htmlを)で開始

VARメニュー、URL、説明、アクション、データ、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 

アンカーがクリックされるたびに、新しい歴史のインスタンスは、履歴スタックにプッシュされると(状態と呼ばれる)オブジェクトが保存されていますlocal URLは変更されますが、ロードは 'event.preventDefault()'メソッドによって停止されます。 さらに、いくつかの情報(URL、説明、およびアクションとして)が更新されます。

次に、 '戻る'と '進む'ボタンを使用すると、history.state(またはevent.stateまたはbrowser.event.state、これはブラウザに依存します)を使用して現在の状態。

最後に、アドレスバーにURL全体を直接入力すると、上記と同じように動作します。htaccessファイル;)私は、この例では、あなたの役に立てば幸い

;)

チャオ

ウィルク

PS:詳細は:

  1. Manipulating the browser history
  2. History object
  3. ここ
+0

素晴らしい! jsfiddleを更新してコードをプラグインできますか? – frenchie

+0

jsFiddleにはいくつかの問題があると思います。なぜなら、アンカーをクリックすると、ページは読み込まれるはずですが...あなたのlocalhostを試してみることをお勧めします。index.htmlとsof.jsファイルをWebサーバーのルートディレクトリ;) それは私のために働く:D – Wilk