SPA单页面原理简单例子演示

hash模式

编辑浏览器地址栏看效果,可以添加#a、#b或者#c

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<style>
		div {
      
      
			display: none;
		}
		.a {
      
      
			display: block;
		}
	</style>
</head>
<body>
	<div id="a" class="a">a</div>
	<div id="b" class="b">b</div>
	<div id="c" class="c">c</div>
</body>
<script>
	function hashchange (hashEvt) {
      
      
    console.log(hashEvt)
		const newHashVal = hashEvt.newURL.split('#')[1]
		const oldHashVal = hashEvt.oldURL.split('#')[1] || 'a'
		document.getElementById(newHashVal).style.display = 'block'
		document.getElementById(oldHashVal).style.display = 'none'
  }

  window.addEventListener('hashchange', hashchange)
</script>
</html>

H5 history

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>
<a class="api">a.html</a>
<a class="api">b.html</a>
</body>
<script>
	document.querySelectorAll('.api').forEach(item => {
      
      
    item.addEventListener('click', (e) => {
      
      
			e.preventDefault()
			if (!!(window.history && window.history.pushState)) {
      
      
        const link = item.textContent
        history.pushState({
      
      name: 'api'}, link, link)
			}
		}, false)
  })

  window.addEventListener('popstate', e => {
      
      
    console.log({
      
      
      location: location.href,
      state: e.state
    })
  }, false)
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40230735/article/details/128853367
今日推荐