html5 history api

1.html5 history api適用場景,我的理解最大的用處是配合ajax使用,使ajax擁有回退、前進的用戶體驗。html

2.代碼(dive into html5中的一個小例子)html5

   1)fer.htmlajax

       

<!DOCTYPE html>
<html>
   <head>
       <title>history api test</title>

   </head>
   <body>
      <aside id="gallery">
          <p class="photonav">
              <a id="photonext" href="casey.html">Next &gt;</a>
              <a id="photoprev" href="adagio.html">&lt;Previous</a>
          </p>
          <figure id="photo">
              <img id="photoimg" src="gallery/1.jpg" alt="fer" width="500" height="375">
              <figcaption>Fer.1972</figcaption>
          </figure>
      </aside>
   <script>
       function setupHistoryClicks(){
           addClicker(document.getElementById("photonext"));
           addClicker(document.getElementById("photoprev"));

       }
       function addClicker(link){
           link.addEventListener("click",function(e){
               swapPhoto(link.href);
               history.pushState(null,null,link.href);
               e.preventDefault();
           },false);
       }
       function swapPhoto(href){
           var req=new XMLHttpRequest();
           req.open("GET",href.split("/").pop(),false);

           req.send(null);
           if(req.status==200){
               document.getElementById("gallery").innerHTML=req.responseText;
               setupHistoryClicks();
               return true;
           }
           return false;
       }
       setupHistoryClicks();
       window.addEventListener("popstate",function(e){
           swapPhoto(location.pathname);
       })
   </script>
   </body>

</html>

 2)casey.htmlapi

 

<aside id="gallery">
    <p class="photonav">
        <a id="photonext" href="adagio.html">Next &gt;</a>
        <a id="photoprev" href="fer.html">&lt;Previous</a>
    </p>
    <figure id="photo">
        <img id="photoimg" src="gallery/casey.jpg" alt="casey" width="500" height="375">
        <figcaption>casey.1972</figcaption>
    </figure>
</aside>

3) adagio.htmlide

<aside id="gallery">
    <p class="photonav">
        <a id="photonext" href="fer.html">Next &gt;</a>
        <a id="photoprev" href="casey.html">&lt;Previous</a>
    </p>
    <figure id="photo">
        <img id="photoimg" src="gallery/1.jpg" alt="fer" width="500" height="375">
        <figcaption>adagio.1972</figcaption>
    </figure>
</aside>
相關文章
相關標籤/搜索