好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

h5History 模式的实例教程

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

一、history.push stat e

history.pushState(state, t IT le, 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",   current State =

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

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

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

<!DOCTY PE  html><html lang="en"><head>< ;m eta charset="UTF-8"><title>HTML5 History 模式(第二版)</title><link rel="stylesheet" type="text/css"  hr ef="css/style.css?1.1.10"><style type="text/css">.cont ai ner-bg{width:1000px; overflow: hidden; m arg in-right: 0 auto;}. pagination {width: 1000px; background-color:  # d8d8d8; h ei ght: 30px; line-height: 30px;}.pa gin ation 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?1.1.10"></script><script type="text/javascript">
    history.replaceState(null, "页面标题", "http://127.0.0.1:3000/lmw/0");//当页面 载入 时候,把 url地址 修改 VAR  se Arch Object = {};/*此对象用来保存下面pushState的URL作为key值,ajax要查询的ID为val
                           *例如:searchObject = {"http://127.0.0.1:3000/lmw/0":0}*/var factory = function(){var addva = document.location.href;//获取完整URLvar query = searchObject[addva];//找到该URL对应的值        query = (query  ==  un define d ? 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].n am e+'</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 ex Press  = require('ex PR ess')var app = e xp ress();
app.use(express.static('./p ub lic'));var router = express.Router();
router.get('/page',function(req,res){var page = req.query.pagetry{var text = fs.rea DF ileSync('./data'+page+'.json');
        res.json(text.toString())
    }catch(err){
        res.send('哈哈!傻逼,没有拉!')    
    }
    
})

app.use(router)

app.listen(3000)

 注意:history.pushState({pageIndex : 1}, "", "http://127.0.0.1:3000/lmw/"+query)这里第三个参数写了完整的绝对路径,如果写成"/lmw/"+query这样的相对路径,会随着query值得增加无限在url后面追加,因为相对路径它一定是相对于当前的URL

服务端放了data0.json,data1.json,data2.json来模拟一下 数据库 取数据, 服务器 更具前端传来的index值(0/1/2),来匹配读取data*. json文件 ,再发给前端

以上就是h5History 模式的实例教程的详细内容,更多请关注其它相关 文章 !

总结

以上是 为你收集整理的 h5History 模式的实例教程 全部内容,希望文章能够帮你解决 h5History 模式的实例教程 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于h5History 模式的实例教程的详细内容...

  阅读:23次