SPA页面

背景:html

  单页 Web 应用 (single-page application 简称为 SPA) 是一种特殊的 Web 应用,它将全部的活动均局限于一个Web页面中;这就表示Web应用被加载出来以后,Web中全部的交互和跳转均不会与服务器发生交互,而是使用JS转换HTML中的内容。服务器

 

实现的原理:app

  1. 使用 hashchange 能够检测路由的变化状况spa

  2. 使用 location.hash 路由,而后根据路由选择须要渲染的页面内容code

 

SPA Demo:htm

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>SPA Demo</title>
 6     <style>
 7  .box {
 8  width: 300px;
 9  height: 300px;
10  background: lightyellow;
11  margin: 0 auto;
12         }
13  .content {
14  width: 100%;
15  height: 100%;
16         }
17     </style>
18 </head>
19 <body>
20     <div class="box">
21         <div class="content"></div>
22         <button>下一页</button>
23     </div>
24     <script>
25  const renderHtml = (text) => { 26  let element = document.querySelector('.content') 27  element.innerHTML = text 28  } 29  const responseForPath = (path) => { 30  let mapper = { 31                 '/0': `<h3>第一个界面</h3>`,
32                 '/1': `<h3>第二个界面</h3>`,
33                 '/2': `<h3>第三个界面</h3>`,
34                 '/3': `<h3>第四个界面</h3>`,
35  } 36             if (path in mapper) { 37                 return mapper[path] 38  } else { 39                 return 'not found'
40  } 41  } 42         // 获取当前的路由,而后根据路由选择须要渲染的内容
43  const render = () => { 44  console.log(location.hash) 45             // 根据路由选择相应的内容
46  let r = responseForPath(location.hash.slice(1)) 47             // 渲染内容
48  renderHtml(r) 49  } 50  const bindEvents = () => { 51             // 给当前窗口绑定 hashchange 事件
52  window.addEventListener('hashchange', (event) => { 53  render() 54  }) 55  } 56         // 给按钮绑定事件,实现页面路由的更换
57  const buttonBindEvent = () => { 58  let ele = document.querySelector('button') 59  ele.addEventListener('click', (event) => { 60  let x = location.hash 61                 // console.log(x)
62                 if (x === '') { 63  location.hash = '/0'
64  } else { 65  console.log(x) 66  let temp = x.slice(2) 67  console.log(temp) 68  temp = (Number(temp) + 1) % 4
69  location.hash = `/${temp}`
70  } 71  }) 72  } 73  const __main = () => { 74  bindEvents() 75  render() 76  buttonBindEvent() 77  } 78         
79         // DOMContentLoaded 事件表示 HTML 已经加载(渲染)到页面中, 这个时候操做 DOM 元素就没有问题
80  document.addEventListener('DOMContentLoaded', () => { 81  __main() 82  }) 83     </script>
84 </body>
85 </html>

 

参考资料:blog

  1.  如何快速开发SPA应用:http://www.javashuo.com/article/p-ozvvulah-cy.html事件

相关文章
相关标签/搜索