欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅析HTML5中的 History 模式

程序员文章站 2022-07-22 20:55:04
这篇文章主要介绍了HTML5中的 History 模式的相关资料,需要的朋友可以参考下... 17-06-22...

最近看到vue-router的html5 history 模式路由的实现,然后顺便又去研究了一下html5 的 history,以下是自己的一些理解,顺便用jquery写 一个实现类似vue-router里面html5 history 模式路由器,以达到练练手,熟悉熟悉的目的。

一、history.pushstate

history.pushstate(state, title, url);

 上面第一和第二个参数可以为空,主要就是第三个参数,表示新历史纪录的地址,浏览器在调用pushstate()方法后不会去加载这个url,新的url不一定要是绝对地址,如果它是相对的,它一定是相对于当前的url

二、history.replacestate

history.replacestate(state, title, url);

window.history.replacestate 和 window.history.pushstate 类似,不同之处在于 replacestate 不会在 window.history 里新增历史记录点,其效果类似于 window.location.replace(url) ,都是不会在历史记录点里新增一个记录点的。

三、window.onpopstate

来监听url的变化

window.addeventlistener("popstate", function() {
    var currentstate = history.state;
    /*
     * 触发事件后要执行的程序
    */                                            
});
//或者
window.onpopstate = function(){}

javascript脚本执行 window.history.pushstate 和 window.history.replacestate 不会触发 onpopstate 事件,在浏览器点击前进或者后退会触发

谷歌浏览器和火狐浏览器在页面第一次打开的反应是不同的,谷歌浏览器奇怪的是回触发 onpopstate 事件,而火狐浏览器则不会

四、下面贴一个类似vue-router的html5模式的例子,纯属加深理解,写的很粗糙。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>html5 history 模式(第二版)</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <style type="text/css">
        .container-bg{width:1000px; overflow: hidden; margin-right: 0 auto;}
        .pagination{width: 1000px; background-color: #d8d8d8; height: 30px; line-height: 30px;}
        .pagination li{width: 100px; height: 30px; background: red; float: left; cursor: pointer; color:#fff; margin: 0 10px 0 0;}
    </style>
</head>
<body>
    <div class="container-bg">
        <ul class="pagination">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <ul class="ptting"></ul>
    </div>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
    history.replacestate(null, "页面标题", "http://127.0.0.1:3000/lmw/0");//当页面载入时候,把url地址修改
    var searchobject = {};/*此对象用来保存下面pushstate的url作为key值,ajax要查询的id为val
                           *例如:searchobject = {"http://127.0.0.1:3000/lmw/0":0}*/
    var factory = function(){
        var addva = document.location.href;//获取完整url
        var query = searchobject[addva];//找到该url对应的值
        query = (query == undefined ? 0 :query);
        //发起ajax加载页面
        $.get("/page?page="+query,function(data){
                    var data2 = json.parse(data);
                    var ele = ""
                    for(var i=0;i<data2.data.length;i++){
                        ele += '<li>'+data2.data[i].name+'</li>'
                    }
                    $('.ptting').html(ele)
                }) 
        };
        //点击分页切换事件
            $(".pagination li").click(function(){
                var query=$(this).index();
                $.get("/page?page="+query,function(data){
                    var data2 = json.parse(data);
                    var ele = ""
                    for(var i=0;i<data2.data.length;i++){
                        ele += '<li>'+data2.data[i].name+'</li>'
                    }
                    $('.ptting').html(ele)                    
                    history.pushstate({pageindex : 1}, "", "http://127.0.0.1:3000/lmw/"+query);
                    //把当前pushstate的url,和ajax查询的值存入对象,以供触发pushstate事件的时候使用
                    searchobject["http://127.0.0.1:3000/lmw/"+query] = query
                })
            })
//浏览器前进或者后退的时候触发popstate事件
if (history.pushstate) {
    window.addeventlistener("popstate", function() {
        factory()                              
    });
    factory()
};
    </script>
</body>
</html>

顺便贴一个node.js中的server代码,为了测试,很随意简单的写了一个

var fs = require('fs')
var path = require('path')
var express = require('express')
var app = express();
app.use(express.static('./public'));
var router = express.router();
router.get('/page',function(req,res){
    var page = req.query.page
    try{
        var text = fs.readfilesync('./data'+page+'.json');
        res.json(text.tostring())
    }catch(err){
        res.send('哈哈!傻逼,没有拉!')    
    }
})
app.use(router)
app.listen(3000)

注意:history.pushstate({pageindex : 1}, "", ")这里第三个参数写了完整的绝对路径,如果写成"/lmw/"+query这样的相对路径,会随着query值得增加无限在url后面追加,因为相对路径它一定是相对于当前的url
服务端放了data0.json,data1.json,data2.json来模拟一下数据库取数据,服务器更具前端传来的index值(0/1/2),来匹配读取data*.json文件,再发给前端

以上所述是小编给大家介绍的html5中的 history 模式,希望对大家有所帮助