原声js实现路由

67 阅读1分钟

单页面应用:顾名思义就是一个html页面,然后根据不同url,展示不同内容。

1.实现思路:

js监听url变化,从而改变特定区域的内容。hash路由是"#/home",hash路由特点是不会重新刷新页面

<style>
  body,ul,li{
    padding: 0;
    margin: 0;
  }

  .header{
   width: 100%;
   height: 100px;
   background-color: rgb(198, 195, 212);
   text-align: center;
   list-style: 100px;
   color: #865a5a;
  }
  .section_left{
    width: 16%;
    height: 500px;
    float: left;
    background-color: rgb(173, 145, 145);
  }
  .section_left ul li{
    list-style: none;
    width: 100%;
    height: 50px;
    line-height: 50px;
    border-bottom: 1px solid #ffffff;
    text-align: center;
   

  }
  .sidebar_right{
    width: 78%;
    float: right;
    margin-right: 3%;
    margin-top: 15px;
    background-color: rgb(105, 90, 90);
    height: 470px;
    line-height: 470px;
    border-radius: 10px;
    color: #e6cdcd;
    text-align: center;
    font-size: 30px;

  }
   
 
  </style>
<body>
  <header class="header">
    <h1>我是头部</h1>
  </header>
  <section class="section_left">
    <ul>
      <li>
        <a href="#/">这是默认菜单</a>
      </li>
      <li>
        <a href="#/html">html学习</a>
      </li>
      <li>
        <a href="#/css">css学习</a>
      </li>
    </ul>
  </section>
  <sidebar class="sidebar_right">
    <h1>我是默认内容</h1>
  </sidebar>

</body>
<script>
 class  Router {
   constructor(){
     this.routers={}
     this.curUrl=''
   }
   init(){
    window.addEventListener('hashchange',this.reloadPage.bind(this))
   }
   reloadPage(){
    this.curUrl=location.hash.substring(1)||'/'
    this.routers[this.curUrl]()
   }
   map(url,callback){
    this.routers[url]=callback

   }
 }
 const router=new Router()
 router.init()
  
 router.map('/',function(){
  const res=document.querySelector('sidebar')
  res.innerHTML='我是html页面'
 })
  
 router.map('/css',function(){
  const res=document.querySelector('sidebar')
  res.innerHTML='css学习'
 })
  
 router.map('/html',function(){
  const res=document.querySelector('sidebar')
  res.innerHTML='html学习'
 })


  </script>