HTML5-History路由

15 篇文章 0 订阅
14 篇文章 0 订阅

现今框架(Vue、React等)内置路由(Router)默认一般为Hash路由,包括我自己搭建的博客路由也使用Hash路由

今天主要记录H5的新增API--History,可以实现不刷新操作页面,通过其中API操作浏览器历史记录

history.pushState(state, title, url);
/* state通常作为页面数据状态值
* title即页面标题,一般都为null
* url即页面中的当前路由 如:wwww.baidu.com/*.html
* 调用即会向浏览器历史记录中插入一条数据
*/
history.replaceState(state, title, url);
/*
* 参数与pushState相同
* 区别:repalce会替换当前url路由,且替换浏览器的历史记录
*/
window.onpopstate = function(event) {};
/**
 * 浏览器前进或后退自动调用popstate函数
 * event-[object对象] 即是pushState或replaceState函数中的参数,
*/
history.go();
/*
*  在浏览器历史记录中前进或后退n条记录
* 当n=0或空时会刷新当前页
*/
history.back();
/**
 * 后退一步
*/
history.forward();
/**
 * 前进一步
*/
history.length;
/**
 * 浏览器历史记录长度
*/

下面放一个小demo

<!DOCTYPE html>
<html class="html">

<head>
    <meta charset='utf-8'>
    <title>HTML5-History</title>
</head>

<body>
    <button onclick="redClick()">red</button>
    <button onclick="blueClick()">blue</button>
    <button onclick="greenClick()">green</button>
    <p class="test">test innerText</p>
    <button onclick="consoleLog()">打印</button>
</body>

<script>
    function redClick() {
        history.pushState({
            color: 'red'
        }, 'red', location.href.split('?')[0] + '?color=red')
        fnHashTrigger({
            color: 'red'
        })
    }

    function blueClick() {
        history.pushState({
            color: 'blue'
        }, 'blue', location.href.split('?')[0] + '?color=blue')
        fnHashTrigger({
            color: 'blue'
        })
    }

    function greenClick() {
        history.pushState({
            color: 'green'
        }, 'green', location.href.split('?')[0] + '?color=green')
        fnHashTrigger({
            color: 'green'
        })
    }

    function fnHashTrigger(state) {
        console.log(state)
        if (state) {
            document.querySelector('.test').style.color = state.color || 'red';
        }
    }
    window.addEventListener("popstate", function (event) {
        fnHashTrigger(event.state);
    });

    function consoleLog() {
        console.log(history)
    }
</script>

</html>

谢谢浏览~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值