zoukankan      html  css  js  c++  java
  • 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);
    })
  • 相关阅读:
    HIDS逐渐的成为主流 java程序员
    怎样做反向域名解析(反向DNS解析)? java程序员
    入侵检测系统的性能的辨别(2) java程序员
    Codeforces Round #146 (Div. 2)
    usaco1.34Prime Cryptarithm
    poj3667 hotel(线段树区间合并)
    poj1330Nearest Common Ancestors(水LCA)
    hdu4135Coprime(容斥原理)
    hdu1541Stars(树状数组)
    usaco 1.43Arithmetic Progressions
  • 原文地址:https://www.cnblogs.com/laneyfu/p/12628578.html
Copyright © 2011-2022 走看看