当前位置:网站首页>原生JS路由,iframe框架
原生JS路由,iframe框架
2022-06-21 15:33:00 【旺仔好吃糖】
文章目录
js单页面路由
hash
原理
基于 hash (location.hash + hashchange事件)
即通过切换hash值(url中 从# 开始到结束的部分)来实现页面的切换
可以通过hashchange事件,监听到hash值的变化,改变 URL 的方式只有这几种:通过浏览器前进后退改变 URL、通过
<a>标签改变 URL、通过window.location改变URL,这几种情况改变 URL 都会触发 hashchange 事件
hash的实现方法
- 设置a标签 , href = ‘#/aaa’,当点击该标签时,会在当前url后添加上"#/aaa",同时触发hashchange事件
- 直接在js中对location.hash = ‘#/aaa’


或者
//定义一个router对象
function Router() {
this.routes = {
};//储存所有的路由
this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
this.routes[path] = callback || function(){
};
};
Router.prototype.refresh = function() {
this.currentUrl = location.hash.slice(1) || '/';
this.routes[this.currentUrl]();
};
Router.prototype.init = function() {
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
//路由初始化
window.Router = new Router();
window.Router.init();
//实例中的应用
var content = document.querySelector('body');
// change Page anything
function changeBgColor(color) {
content.style.backgroundColor = color;
}
Router.route('/', function() {
changeBgColor('white');
});
Router.route('/blue', function() {
changeBgColor('blue');
});
Router.route('/green', function() {
changeBgColor('green');
});
新建一个router实例,进行初始化,然后进行url与callback的绑定,就可以在hash发生改变时触发相应的值
history
基于 history.pushState() + popState事件
原理
pushState()方法是修改url的地址,popstate监听地址的改变,但是手动的进行pushState不会触发popstate事件
- pushState()方法,添加历史条目,history.pushState(state, title, url),需要三个参数:对象state,下一个页面的title,动态改变的url(可选)
- replaceState()方法,history.replaceState(state, title, url),直接替换
实现方法
html代码
<body>
<ul>
<li><a href="#/">turn white</a></li>
<li><a href="#/blue">turn blue</a></li>
<li><a href="#/green">turn green</a></li>
</ul>
</body>
js代码
<script type="text/javascript">
(function(){
var content = document.querySelector('body');
// 改变背景颜色 封装函数
function changeBgColor(color){
content.style.backgroundColor = color
}
// history路由跳转
var li = document.querySelectorAll('li')
console.log(li);
history.replaceState(null,null,'')//最开始的状态,采用replace直接替换
li[0].addEventListener('click',function(){
history.pushState(null,null,'#/')//之后的状态,需要保存
changeBgColor('white')
})
li[1].addEventListener('click',function(){
history.pushState(null,null,'#/blue')//之后的状态,需要保存
changeBgColor('blue')
})
li[2].addEventListener('click',function(){
history.pushState(null,null,'#/green')
changeBgColor('green')
})
})()
iframe框架
iframe的用途
iframe : 可以实现在网页中套网页,是一个html标签 (https 的网页不可以嵌套 http 的网页)
iframe常用属性
frameborder :是否显示边框 yes/no
width :宽度
height :高度
name :框架的名称,window.frames[name]时专用的属性
src :在iframe中显示的目标网站的url,(可以是页面地址,也可以是图片的地址)
scrolling : 是否显示滚动条,yes/no/auto
sandbox : 安全限制
//将href.html嵌入
//href.html部分代码
<li><a href="http://www.bilibili.com" target="myframe">bili</a></li>
<li><a href="http://www.taobao.com" target="myframe">淘宝</a></li>
-------------------------------------------------------
//iframe.html代码 使b站页面和淘宝页面可以在框架中显示
<iframe src="href.html" frameborder="0" width="10%" height="700px"></iframe>//将href.html放入框架中
<iframe frameborder="0" name="myframe" width="80%" height="700px" ></iframe>
给a链接设置相同的target,使iframe中的name属性的值与target值相同,即可通过target为a链接到指定框架(通过name)
iframe的js操作(同域)
在父页面中获取iframe子页面的元素
<body>
<iframe src="text2.html" frameborder="0" id="one" name="one" width="100" height="300"></iframe>
<iframe src="text3.html" frameborder="0" id="two" name="two" width="100" height="300"></iframe>
</body>
//获取iframe的window对象
var iwindow = document.getElementById('one').contentWindow
//获取iframe的document对象
var idoc = iwindow.document.getElementById(xxx)
或者 结合name属性
var idoc = window.frames['one'].document.getElementById(xxx
var idoc = window.frames[1].document.getElementById(xxx
//frames[]中可以写索引也可以写 name属性的值
在iframe子页面中获取父页面的元素
var idoc=window.parent.document.getElementById();
注:此时,在本地用绝对路径直接运行HTML文件(如 file:///D:/code/vscodeworkspace/iframe/text.html),会报错,是因为同文件中的操作是按照跨域处理的,在编辑器中按照网址打开即可
边栏推荐
- Office operation sorting notes
- GO语言-指针
- Niuke - real exercise-01
- Online keyboard key detection tool
- Operator Tour (I)
- In 2021, China's deposit balance continued to grow, and the balance of RMB and foreign currency deposits reached a record high [figure]
- Analysis of China's social financing scale and financing structure in 2021: RMB loans to the real economy account for more than 60%[figure]
- Basic concepts of database
- Teach you to stop visiting a website
- Jason Basics
猜你喜欢

Best practice | how to use Tencent cloud micro build to develop enterprise portal applications from 0 to 1

Phantom star VR product details 31: escape from the secret room

GO语言-接口

Phantom star VR product details 34: Happy pitching

Non local network: early human attempts to tame transformer in CV | CVPR 2018

HSV color model and color component range in opencv

PCA dimension reduction application of OpenCV (I)

Gather high-quality ar application developers, and help the AR field prosper with technology

Stm32l431 immediate sleep mode (code + explanation)

Learn upward management and four questioning skills to get twice the result with half the effort
随机推荐
Office operation sorting notes
Telnet batch test (II): key codes for the implementation of Telnet batch test script
What is a good product for children's serious illness insurance? Please recommend it to a 3-year-old child
Live long to see the true chapter
Mysql5.7 add SSL authentication
Best practice | how to use Tencent cloud micro build to develop enterprise portal applications from 0 to 1
Gee Registration Guide
Is it safe to open a securities account by downloading the app of qiniu school? Is there a risk?
利用并查集求最小生成树
For the first time in China, Tsinghua and other teams won the wsdm2022 only best paper award, and Hong Kong Chinese won the "time test Award"
C language selection type supplement
Non local network: early human attempts to tame transformer in CV | CVPR 2018
Browser evaluation: a free, simple and magical super browser - xiangtian browser
通过编译内核的方式增加系统调用
微服务架构带来的分布式单体
Kubeneters installation problems Collection
Build an efficient and scalable result cache
2022awe opened in March, and Hisense conference tablet was shortlisted for the review of EPLAN Award
Basic concepts of database
[Yugong series] February 2022 wechat applet -app Debug JSON configuration attribute