某个页面禁止使用浏览器返回demo

2019-12-30  本文已影响0人  清夜银月
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>某个页面禁止使用浏览器返回demo</title>
    <style>
        .page {
            height: 1000px;
        }

        .page1 {
            background-color: red;
        }

        .page2 {
            background-color: yellow;
        }

        .page3 {
            background-color: blue;
        }

        ul {
            position: fixed;
        }
    </style>
</head>
<body onload="load()">
<ul>
    <li><a onclick="aClick('#page1')">红色页面</a></li>
    <li><a onclick="aClick('#page2')">黄色页面</a></li>
    <li><a onclick="aClick('#page3')">蓝色页面</a></li>
</ul>
<div id="page1" class="page page1"></div>
<div id="page2" class="page page2"></div>
<div id="page3" class="page page3"></div>
<script>
    //监听历史记录发生变化
    window.onpopstate = function (event) {
        if (event.state === '#page2') {
            window.history.pushState('#page2', null, '')
        }
    };

    function aClick(hash) {
        window.location.hash = hash
        if (window.location.hash === '#page2') {
            window.history.pushState('#page2', null, '')
            window.history.pushState('#page2', null, '')//必须插入两条
        }
    }
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读