html5 history api 实现无刷新浏览以及历史记录管理

本文介绍了一个使用HTML、CSS和JavaScript实现的简单网页布局,包括左侧导航栏和右侧的内容展示区域。通过监听点击事件来改变当前显示的页面内容,并利用浏览器的历史API实现了前进后退的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="UTF-8">
   <title></title>
   <style>
      body, html, ul, li, dl, dt, dd {
         padding: 0px;
         margin: 0px;
      }
      nav {
         width: 100px;
         display: block;
         float: left;
         background-color: #c3c3c3;
      }
      nav ul {
         list-style-type: none;
         overflow: hidden;
      }
      nav li {
         padding: 0px 6px;
         font-size: 20px;
         margin-bottom: 10px;
      }
      nav li:first-child {
         margin-top: 10px;
      }
      nav li a {
         text-decoration: none;
      }
      article {
         display: block;
         margin-left: 100px;
         padding: 10px;
         background-color: #ffffff;
      }
   </style>
</head>
<body>
<aside>
   <nav>
      <ul>
         <li><a href="/home">home</a></li>
         <li><a href="/about">about</a></li>
         <li><a href="/photos">photos</a></li>
      </ul>
   </nav>
</aside>
<article>
   <dl>
      <dt>title:</dt>
      <dd class="title"></dd>
      <dt>url:</dt>
      <dd class="url"></dd>
      <dt class="description">description:</dt>
      <dd></dd>
   </dl>
</article>

<script src="lib/jquery-1.11.2.min.js"></script>
<script src="js/index.js"></script>
</body>
</html>

$(document).ready(function () {
   function update (info) {
      $(".title").html(info.title);
      $(".url").html(info.url);
      $(".description").html(info.description);
   }
   var stateObj = {
      home: {
         title: "home",
         url: "/home",
         description: "this is home page"
      },
      about: {
         title: "about",
         url: "/about",
         description: "this is about page"
      },
      photos: {
         title: "photos",
         url: "/photos",
         description: "this is photos page"
      }
   }

   $("nav").on("click", "a", {}, function (event) {
      var state = event.target.getAttribute("href").replace(/\//, "");
      event.preventDefault();
      history.pushState(stateObj[state], "", event.target.href);
      update(stateObj[state]);
   })

   window.addEventListener("popstate", function () {
      var state = history.state;

      update(state);
   });

   history.pushState(stateObj["home"], "", "/home");
   update(stateObj["home"]);
})


转载于:https://my.oschina.net/u/1992917/blog/621176

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值