1. 程式人生 > >HTML頁面的雜湊(hash)路由原理+原生js案例

HTML頁面的雜湊(hash)路由原理+原生js案例

<!--
* 場景:不重新整理頁面,對頁面的區域性內容進行更改
*方案1:ajax 方法
*方案2:雜湊(hash)路由原理
*方案2講解:監聽瀏覽器的url中的hash(url的#後面的文字——錨文字)值,進行更改內容
-->
<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>js原生頁面hash路由</title>
    <style>
        ul{
            float: left;
            width: 200px;
        }
        li{
            list-style: none;
            padding: 8px 15px;
            background: #B9CBF7;
            text-align: center;
        }
        a{
            color: #86FF00;
        }
        #result{
            height: 200px;
            margin-left: 200px;
            line-height: 200px;
            font-size: 30px;
            text-align: center;
            color: #D64BD3;
        }
    </style>
</head>
<body>
    <div class="container">
        <ul>
            <li><a href="#/">首頁</a></li>
            <li><a href="#/product">產品</a></li>
            <li><a href="#/server">服務</a></li>
        </ul>
        <div id="result"></div>
    </div>
    <script>
        //路由構造器
        function Router() {
            //接受所有的配置路由內容:錨 和 函式方法
            this.routes = {};
            //接受 改變後的 hash值
            this.curUrl = '';
            //將定義的所有路由和函式方法 傳給 routes
            this.route = function (path, callback) {
                this.routes[path] = callback || function () {};
                console.log('routes[path]:'+this.routes[path])
            };
            //hash 值改變時觸發的 函式方法
            this.refresh = function () {
                //獲取改變的hash值(url中錨 # 號後面的文字)
                this.curUrl = location.hash.slice(1) || '/';
                this.routes[this.curUrl]();
                console.log('location.hash:'+location.hash);
                console.log('curUrl:'+this.curUrl);
                console.log('this.routes[this.curUrl]:'+this.routes[this.curUrl])
            };
            //監聽load(載入url)、hashchange(hash改變)事件
            this.init = function () {
                window.addEventListener('load',this.refresh.bind(this),false);
                window.addEventListener('hashchange',this.refresh.bind(this),false)
            }
        }
        var R = new Router();//使用Router構造器

        R.init();//監聽時間

        var res = document.getElementById('result');//讀取id為result的元素
        //定義所有需要用的 路由:hash值 和 載入的內容
        R.route('/',function () {
            res.style.background = 'blue';
            res.innerHTML = '這是首頁';
        })
        R.route('/product',function () {
            res.style.background = 'orange';
            res.innerHTML = '這是產品頁';
        })
        R.route('/server',function () {
            res.style.background = 'black';
            res.innerHTML = '這是服務頁';
        })
    </script>
</body>
</html>