Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SPA单页面web应用的一些简介 #230

Open
confidence68 opened this issue Dec 28, 2016 · 0 comments
Open

SPA单页面web应用的一些简介 #230

confidence68 opened this issue Dec 28, 2016 · 0 comments
Labels

Comments

@confidence68
Copy link
Owner

SPA单页面应用

单页面web应用,在目前市面上应用越来越广泛,当然,实现方式也是有很多。有些单页面开发是通过React、Vue、Node、Web Components、Webpack等来实现。 当然也有一些其他的实现方式。但是大多数是通过hash或者pushsate来实现的。关于pushsate,我之前的一篇文章:ajax无刷新页面切换,历史记录后退前进解决方案,已经做了介绍。感兴趣的可以去看一下!为什么很多网站都在用单页面web?那是因为主要看中的是单页面web应用,无刷新界面,给用户体验原生的应用感觉。但是也有其缺点和不足。今天主要介绍一下简单的单页面web应用。

最简答的实现

最简答的实现方式是我们结合hash,采用的是div切换显示和隐藏,来实现。

运用如下事件监听hash变化

window.onhashchange

大家可以将如下代码贴到页面中,测试一把

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <style type="text/css">
    body {
      height: 500px;
      width: 100%;
      margin: 0;
      padding: 0;
    }
    div {
      width: 100%;
      height: 100%;
      position: absolute;
      font-size: 500px;
      text-align: center;
      display: none;
    }
    .a {
        background-color: pink;
        display: block;
    }
    .b {
      background-color: red;
    }
    .c {
    background-color: gray;
    }
  </style>
</head>
<body>
  <div id="A" class="a haorooms">A</div>
  <div id="B" class="b haorooms">B</div>
  <div id="C" class="c haorooms">C</div>
</body>
<script type="text/javascript">
function hashChanged(hashObj) {
  //变化之后的url
  var newhash = hashObj.newURL.split('#')[1];
  //变化之前的url
  var oldhash = hashObj.oldURL.split('#')[1];
  //将对应的hash下界面显示和隐藏
  document.getElementById(oldhash).style.display = 'none';
  document.getElementById(newhash).style.display = 'block';
}
//监听路由变化
window.onhashchange = hashChanged;
</script>
</html> 

默认的显示是A,地址中包含#A 当浏览器地址切换为#B的时候,ID是B的div显示,其他的div隐藏。

HTML5 History API 实现

这个我之前文章介绍过相关API ,地址是:http://www.haorooms.com/post/ajax_historybackprev

这里我们以haorooms为例,打开haorooms,地址栏是http://www.haorooms.com/ 。接下来打开F12 Console,输入:

history.pushState({ a: 1, b: 2 }, null, "http://www.haorooms.com/historytest");

可以发现,url已经变成我们输入的url了,但页面并没有刷新,也没有发出任何请求。现在再输入history.state,就可以看到我们刚刚传过来的第一个参数state了。

我们可以通过历史返回到上一页。

通过HTML5 History API,我们来实现页面跳转,实现简单的单页面web应用。

操纵浏览器的历史记录

前面的课程已经讲过,假如还不清楚,可以看 https://developer.mozilla.org/zh-CN/docs/DOM/Manipulating_the_browser_history

关于单页面web应用,就先说到这里!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant