history.back():上一條 history.forward():下一條 history.go():相對於當前頁面的前進或後退php
新增長的api: history.pushState() :追加歷史html
history.replaceState(); 替換歷史jquery
上面兩個函數都有3個參數 (1.存數據 null 2.標題 null 記錄的地址)ajax
window.onpopstate=function(){json
監聽歷史切換事件.api
} 服務器
單頁面應用程序:SPA (single page application)數據結構
實現方案:(1) 哈希 hash (2)歷史追加 特色:改變地址欄是不會跳轉的.app
ajax 渲染頁面 優勢:提升用戶體驗 缺點:不利於seo異步
解決方案:ajax渲染頁面的同時,更改地址欄(地址欄在服務器端必定要有相對應的頁面)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>history</title>
<style>
*{
padding: 0;
margin: 0;
}
body {
background-color: #F7F7F7;
font-family: Arial;
}
header {
background: #242424;
border-bottom: 1px solid #000;
}
.wrapper{
width: 1100px;
height: 70px;
margin: 0 auto;
}
header .wrapper h1{
float: left;
width: 176px;
height: 69px;
background: url(images/topbar.png) no-repeat 0 0;
font-size: 0;
}
header .wrapper ul{
list-style:none;
}
header .wrapper ul li{
float: left;
height: 70px;
}
header .wrapper ul li.now,
header .wrapper ul li:hover{
background: #12b7f5;
}
header .wrapper ul li a{
padding: 0 20px;
display: block;
color: #fff;
line-height: 70px;
text-decoration: none;
}
.content{
width: 1100px;
margin: 0 auto;
font-size: 100px;
text-align: center;
}
</style>
</head>
<body>
<header>
<div class="wrapper">
<h1>網易雲音樂</h1>
<ul>
<li data-page="index" class="<?php echo $page=='index'?'now':'' ?>" ><a href="index.php">發現音樂</a></li>
<li data-page="my" class="<?php echo $page=='my'?'now':'' ?>"><a href="my.php">個人音樂</a></li>
<li data-page="friend" class="<?php echo $page=='friend'?'now':'' ?>"><a href="friend.php">朋友</a></li>
</ul>
</div>
</header>
<div class="content">
<?php echo $html ?>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/index.js"></script>
</body>
</html>
/*1.ajax異步加載 渲染頁面*/
/*2.渲染什麼頁面須要和後臺提供的地址保持一致*/
/*3.切換歷史渲染頁面*/
$(function () {
$('.wrapper').on('click','a',function () {
//渲染頁面 頁面標識
var page = $(this).parent().data('page');
render(page);
/*地址保持一致*/
/*追加地址 並且這個地址後臺必定要存在*/
var historyUrl = $(this).attr('href');
history.pushState(null,null,historyUrl);
return false;
});
/*監聽切換歷史*/
window.onpopstate = function () {
/*獲取地址欄信息*/
console.log(location.pathname);
/*根據信息判斷須要加載什麼頁面的內容*/
var pathname = location.pathname;
var page = 'index';
if(pathname.indexOf('index.php') > -1 ){
page = 'index';
}else if(pathname.indexOf('my.php') > -1){
page = 'my'
}else if(pathname.indexOf('friend.php') > -1){
page = 'friend';
}
render(page);
}
});
var render = function (page) {
/*怎麼調用ajax 請求方式 請求地址 請求參數 返回數據結構和意義 */
/*發出請求*/
$.ajax({
type:'get',
url:'api/data.php',
data:{
page:page
},
dataType:'json',
success:function (data) {
/*渲染頁面*/
/*選中樣式*/
$('[data-page]').removeClass('now');
/*data返回了當前頁面的標識*/
$('[data-page="'+data.page+'"]').addClass('now');
/*網頁內容*/
$('.content').html(data.html);
}
});
}
效果圖: