SPA路由控制系统v1.3.11

2026年01月26日/ 浏览 12

特点

功能特点

支持动态更新网页title只需简单地修改Hash值,即可触发界面跳转支持Hash传参,实现带参跳转界面支持记录界面滚动位置,当再次载入某界面时,可恢复该界面滚动位置实现多URL入口型的组件化开发,可使用URL精准定位到SPA的某个状态界面跳转支持淡入淡出等动画效果(自行设置)

其它特性

采用Hash监听的形式,监听SPA状态的改变,相比History方式,免去了配置sitemap的过程,实现单个HTML即可完成的路由操作Hash传参时,使用“/”分隔参数,URL外观更为友好相比History方式,使用Hash监听,可避免多次增加相同的历史记录本程序短小精悍,使用简单方便,对各种JavaScript框架都能很好地适应和支持(目前示例代码是配合jQuery完成的,如果要搭配其它框架,只需将相应的jQuery操作替换成对应框架的操作即可)

使用说明

scrolls函数必须在界面组件加载完成(如Ajax完成)后调用,以实现恢复界面滚动位置(第26行)传参示例:location.hash = /list/12345/234/hash通过“/”分割后,下标1处的值为target,即目标界面标识,每个标识应当分别作出判断,并执行相应的载入事件(第21行),每当匹配到target,需要执行document.title = 标题 修改界面标题HTML网页中,界面必须使用 <div class="p-xxx p-oyp"></div> 进行定义,不同界面的组件需要放在不同的界面中p-oyp类匹配所有界面,p-xxx类匹配某一个界面本程序由欧阳鹏原创设计,官网:www.ouyangpeng.top

触发:界面跳转

JavaScript方式

location.hash = /about/

HTML方式

<a onclick="location.hash = /about/">关于</a>

HTML基础结构

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hash路由</title> <style> div.p-oyp { display: none; } </style> <script src="./js/jquery.min.js"></script> <script> $(document).ready(function () { $("<link>").attr({ rel: "stylesheet", type: "text/css", href: "css/index.css?_=" + new Date().getTime() }).appendTo("head") $.getScript(./js/index.js) }) </script> </head> <body> <div class="p-home p-oyp"> 主页 <button onclick="location.hash = /about/">关于</button> <a href="#/about/">关于</a> </div> <div class="p-about p-oyp"> 关于 <button onclick="location.hash = /home/">主页</button> </div> </body> </html>

脚本内容

// 后端API基础路径 调用API时可引用该路径 var baseUrl = http://app.ouyangpeng.top:520/ function scrolls(hash) { // 获取滚动位置 try { var scroll = JSON.parse(localStorage.yuzhang_scrollData)[JSON.stringify(hash)] var scroll = scroll == undefined ? 0 : scroll } catch { localStorage.yuzhang_scrollData = JSON.stringify({}) var scroll = 0 } scrollTo(0, scroll) } function router(hash) { // 获取目标界面标识 var target = hash == ? home : hash[1] // 交换界面显示 $(.p-oyp).hide() $(.p- + target).fadeIn() // 判断目标界面标识 执行对应模块的载入事件 if (target == home) { document.title = 主页 // 界面载入事件 // ... $.getJSON(api/home.json, function (data) { scrolls(hash) }) } else if (target == about) { document.title = 关于 // 界面载入事件 // ... scrolls(hash) } else if (target == login) { document.title = 登录 // 界面载入事件 // ... scrolls(hash) } } window.addEventListener(hashchange, function (event) { // 监听Hash改变 通过location.hash=xxx可触发 var hash = new URL(event.newURL).hash.split(/) router(hash) }) $(document).ready(function () { router(location.hash.split(/)) // 公共载入事件 // ... // 每次滚动界面 记录滚动位置 $(document).scroll(function () { var scrollData = JSON.parse(localStorage.yuzhang_scrollData) scrollData[JSON.stringify(location.hash.split(/))] = $(document).scrollTop() localStorage.yuzhang_scrollData = JSON.stringify(scrollData) }) })

picture loss