单页 hash 跳转


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>单页hash跳转title>
head>
<body>
<script>
window.addEventListener("DOMContentLoaded", function(){
	//DOM树构建完成后执行下面的代码
	
	function router(option){
		var hash = location.hash.slice(1) || "/";
		option[hash]();
	} 

	function on(events,callback){
		var ev = events.split(' ');
		for(var i in ev){
			window.addEventListener(ev[i],callback)
		}
	}
	var content = document.querySelector('.content');

	// 刷新文档 或hash改变的时候调用 router 函数
	on('load hashchange',function(){router({

			"/":function(){
				content.innerHTML = "home";
			},
			"/about":function(){
				content.innerHTML = "about us";
			},
			"/news":function(){
				content.innerHTML = "news";
			},
			"/product":function(){
				content.innerHTML = "product";
			}
		})
	})
})
script>
	<div class="container">
		<nav class="nav">
			<a href="#/">homea>
			<a href="#/news">newsa>
			<a href="#/product">producta>
			<a href="#/about">about usa>
		nav>
		<div class="content">
			
		div>
	div>
<style>
	.container{
		width: 960px;
		min-height: 400px;
		background: #eee;
		margin: 0 auto;
		border-radius: 15px;
		overflow: hidden;
	}
	.nav{
		width: 100%;
		height: 80px;
		line-height: 80px;
		background: #ccc;	
		text-align: center;
	}
	.nav a{
		margin:0 20px; 
	}
	.content{
		text-align: center;
		font-size: 60px;
		font-weight: bold;
		padding: 50px;
	}
style>
body>
html>

你可能感兴趣的:(javaScript)