hash

class HashRouter {
    constructor(){
        //hash --- > callback
        this.routes={};
        // this.routes = {
        //   '/home':fn1,
        //   '/news':fn2
        // };
        this.currentHash=''; //保存当前的hash
        // var _this = this; //第一种方式
        // window.addEventListener('hashchange',function(){
        //     console.log('kkkk');
        //     _this.hashChangeUrl();
        // },false);

        //第二种方式:
        //  window.addEventListener('hashchange',this.hashChangeUrl.bind(this),false);

        //第三种方式箭头函数
        window.addEventListener('hashchange',()=>{
            this.hashChangeUrl();
        },false);
        // false :冒泡

        //页面加载的事件
        window.addEventListener('load',()=>{
            this.hashChangeUrl();
        },false)
    }
    //path路径和callback函数对应起来
    route(path,callback) {
        this.routes[path] = callback;
    }
    hashChangeUrl(){
        
        //获取当前hash 
        // location.hash 获取的值为:"#/a, 因此 location.hash.slice(1) = '/a' 这样的
        this.currentHash = location.hash.slice(1);

        //当前hash所对应的回调函数
        this.routes[this.currentHash](this.currentHash);
    } 
}

var router = new HashRouter();
const body = document.querySelector('body');

function changeColor(color,html,data){
    
    body.style.backgroundColor=color;
    var activedM = mainMenu.querySelector('a.active');
    activedM && activedM.classList.remove('active');
    mainMenu.querySelector(`a[href="#${data}"]`).classList.add('active');
    content.innerHTML = html;

}
router.route('/',function(data){
    changeColor('red',`<div>我是首页 <p>测试</p></div>`,data);
})
router.route('/home',function(data){
    changeColor('red',`<div>我是首页 <p>测试</p></div>`,data);
})
router.route('/news',function(data){
    changeColor('green',`<div>我是新闻页 <p>测试2</p></div>`,data);
})
router.route('/product',function(data){
    changeColor('blue',`<div>我是产品页 <p>测试3</p></div>`,data);
})
原文地址:https://www.cnblogs.com/laneyfu/p/12628578.html