码迷,mamicode.com
首页 > Windows程序 > 详细

html5 history api

时间:2016-04-24 14:16:34      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

1.html5 history api适用场景,个人理解最大的用处是配合ajax使用,使ajax拥有回退、前进的用户体验。

2.代码(dive into html5中的一个小例子)

   1)fer.html

       

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

 

<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.html

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

 

html5 history api

标签:

原文地址:http://www.cnblogs.com/sunxuejiao/p/5426813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!