前端小白之每天學習記錄----簡單的原生js路由


路由:
根據不同的url 顯示 不同的內容
方法:
hash(錨鏈接)實現路由
history對象

1.首先要了解什么是hash,在這里你可以認為hash就是網址后面加上的 #/xxx

當<a>標簽被點擊時

<a href="#/html">ches</a>
會在原網址后面加上<a>里面herf的內容,當該內容改變時,會產生一個事件 onhashchange

話不多說,直接上代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        window.onload = function(){
            //當hash發生變化的時候, 會產生一個事件 onhashchange
            window.onhashchange = function(){
                alert( '你的hash改變了' );
                //location對象是 javascript內置的(自帶的)
                console.log( location );
            }
        }
    </script>
</head>
<body>
   <a href="#/html">html</a> 
   <a href="#/css">css</a> 
</body>
</html>

  

2.實現一個簡單的路由

location對象:

location對象是 javascript內置的(自帶的)

location 對象包含有關當前 URL 的信息。(也就是網址)

以下代碼可以讓網頁跳轉到百度:

window.location="https://www.baidu.com/";

一個簡單的路由

實現的功能:點擊時從1-33里隨機出現五個數,並按照這五個隨機數改變hash,在按鈕下方顯示五個隨機數

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>

        window.onload = function(){
            var oBtn = document.querySelector("input");//獲取按鈕
            var oDiv = document.querySelector("div");//獲取隨機數的輸出div盒子
            //33->max  5->num
            function buildNum( max, num ){       //這個函數返回   1到33選出的5個隨機數結合的數組
                var arr = [];
                for( var i = 0; i < max; i++ ){
                    arr.push( i + 1 );
                }      //1-33數字集合的數組
                var target = []; 
                for( var i = 0; i < num; i++ ){
                    target.push( arr.splice( Math.floor( Math.random() * arr.length ), 1 ) );
                }    //從1-33這33個數字中 隨機選出5個數放入target數組
                return target;
            }
            oBtn.onclick = function(){  
                var num = buildNum( 33, 5 );  
                // oDiv.innerHTML = num; 
                location.hash = num;    //點擊時吧網址的hash改變成數組  eg:#20,14,6,22,30
            }
            window.onhashchange = function(){
                oDiv.innerHTML = location.hash.substring(1);//在div里面輸出5個隨機數  eg:20,14,6,22,30
            }
        }
    </script>
</head>
<body>
    <input type="button" value="33選5">
    <div></div>
</body>
</html>

  3.簡單路由的運用 (簡單框架雛形的運用) (簡單的html5標簽的運用)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        header,
        footer {
            height: 100px;
            background: #ccc;
        }

        section {
            width: 60%;
            height: 400px;
            background: #eee;
            float: left;
        }

        sidebar {
            width: 40%;
            height: 400px;
            background: #999;
            float: left;
        }

        .clear {
            clear: both;
        }
    </style>
</head>

<body>
    <header>
        頭部
    </header>
    <section>
        <ul>
            <li><a href="#/">啥都沒有</a></li>
            <li><a href="#/html">html</a></li>
            <li><a href="#/css">css</a></li>
            <li><a href="#/javascript">javascript</a></li>
        </ul>
    </section>
    <sidebar>
        右邊
    </sidebar>
    <div class="clear"></div>
    <footer>
        底部
    </footer>
    <script>
        //框架雛形:1.用一個立即表達式把框架包起來,避免代碼污染(定義的變量..等重復使用)
        //         2.在立即表達式里定義一個構造函數(這里指var Router);
        //         3.最后加上語句window.objec = functionName;把函數暴露出來,
        //           附加到window對象上面這樣(這里指window.oRou );
        //         4.在構造函數的原型對象上添加函數(init,reloadPage...)
        //         5.用第3步附在window的構造函數構建一個新對象,//var oRouter2 = new oRou();
        //           這個對象(oRouter2)就可以使用剛剛第4步添加的函數了;

        (function () {    //立即表達式:(function(){代碼內容})();
            var Router = function () {    //構造函數
                /*
                    this.routes['/'] = function(){}    
                    this.routes['/html'] = function(){}
                */
                this.routes = {};//用來保存路由
                this.curUrl = ''; //獲取當前的hash
            }
            Router.prototype.init = function () { //監聽路由變化 當hash變化時調用reloadPage函數
                //call,apply
                window.addEventListener('hashchange', this.reloadPage.bind(this));
                //第一個this指向window,bind里面的this指向調用這個函數的對象(這里是oRouter2)
            }
            Router.prototype.reloadPage = function () {
                this.curUrl = location.hash.substring(1) || '/';//獲取當前hash的值(去掉#)
                this.routes[this.curUrl]();      //運行當前hsah值對應的函數
            }
            Router.prototype.map = function (key, callback) { //保存路由對應的函數:
                this.routes[key] = callback;  //key表示hash的值(去掉#),callback表示當前hash對應的函數
                // console.log( this.routes );
            }
            window.oRou = Router;
        })();


        var oRouter2 = new oRou();
        oRouter2.init();
        oRouter2.map('/', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = '你點,你再點,你點點點';
        });
        oRouter2.map('/html', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = '狂拽 酷炫 吊炸天 的html';
        });
        oRouter2.map('/css', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = '狂 拽 酷 炫 吊 炸 天 的css';
        });
        oRouter2.map('/javascript', function () {
            var oSidebar = document.querySelector("sidebar");
            oSidebar.innerHTML = '狂拽酷炫吊炸天的javascript';
        });
    </script>
</body>

</html>

 

實現效果:點擊時,右邊的部分會根據點擊的不同而改變。

  

 

  

<!DOCTYPE html >
< html lang= "en" >

< head >
< meta charset= "UTF-8" >
< title >Document </ title >
< style >
header,
footer {
height: 100px;
background: #ccc;
}

section {
width: 60%;
height: 400px;
background: #eee;
float: left;
}

sidebar {
width: 40%;
height: 400px;
background: #999;
float: left;
}

.clear {
clear: both;
}
< / style >
</ head >

< body >
< header >
頭部
</ header >
< section >
< ul >
< li >< a href= "#/" >啥都沒有 </ a ></ li >
< li >< a href= "#/html" >html </ a ></ li >
< li >< a href= "#/css" >css </ a ></ li >
< li >< a href= "#/javascript" >javascript </ a ></ li >
</ ul >
</ section >
< sidebar >
右邊
</ sidebar >
< div class= "clear" ></ div >
< footer >
底部
</ footer >
< script >
//框架雛形:1.用一個立即表達式把框架包起來,避免代碼污染(定義的變量..等重復使用)
// 2.在立即表達式里定義一個構造函數(這里指var Router);
// 3.最后加上語句window.objec = functionName;把函數暴露出來,
// 附加到window對象上面這樣(這里指window.oRou );
// 4.在構造函數的原型對象上添加函數(init,reloadPage...)
// 5.用第3步附在window的構造函數構建一個新對象,//var oRouter2 = new oRou();
// 這個對象(oRouter2)就可以使用剛剛第4步添加的函數了;

( function(){ //立即表達式:(function(){代碼內容})();
var Router = function(){ //構造函數
/*
this.routes['/'] = function(){}
this.routes['/html'] = function(){}
*/
this.routes = {}; //用來保存路由
this.curUrl = ''; //獲取當前的hash
}
Router.prototype.init = function(){ //監聽路由變化 當hash變化時調用reloadPage函數
//call,apply
window.addEventListener( 'hashchange', this.reloadPage.bind( this) );
//第一個this指向window,bind里面的this指向調用這個函數的對象(這里是oRouter2)
}
Router.prototype.reloadPage = function(){
this.curUrl = location.hash.substring( 1) || '/'; //獲取當前hash的值(去掉#)
this.routes[ this.curUrl](); //運行當前hsah值對應的函數
}
Router.prototype.map = function( key, callback ){ //保存路由對應的函數:
this.routes[key] = callback; //key表示hash的值(去掉#),callback表示當前hash對應的函數
// console.log( this.routes );
}
window.oRou = Router;
})();
 
 
var oRouter2 = new oRou();
oRouter2.init();
oRouter2.map( '/', function(){
var oSidebar = document.querySelector( "sidebar");
oSidebar.innerHTML = '你點,你再點,你點點點';
});
oRouter2.map( '/html', function(){
var oSidebar = document.querySelector( "sidebar");
oSidebar.innerHTML = '狂拽 酷炫 吊炸天 的html';
});
oRouter2.map( '/css', function(){
var oSidebar = document.querySelector( "sidebar");
oSidebar.innerHTML = '狂 拽 酷 炫 吊 炸 天 的css';
});
oRouter2.map( '/javascript', function(){
var oSidebar = document.querySelector( "sidebar");
oSidebar.innerHTML = '狂拽酷炫吊炸天的javascript';
});



< / script >
</ body >

</ html >


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM