前端页面跳转的6大类方法及其使用场景特性分析
前端页面跳转的方法有很多种,总有一种适合你:
a标签跳转
在当前页面打开:
<a href="https://www.baidu.com">跳转</a>
在当新窗口打开,设置target属性为_blank:
<a href="https://www.baidu.com" target="_blank">跳转</a>
适用场景:
- 页面中跳转固定的地址
js中模拟a标签跳转
function imitateClick(url){
let aEle = document.createElement("a");
aEle.setAttribute("href", url);
aEle.setAttribute("target", "_blank");
aEle.setAttribute("id", "previewJumpEle");
// 防止重复添加
if (!document.getElementById("previewJumpEle")) {
document.body.appendChild(aEle);
}
// 模拟点击
aEle.click();
(aEle.remove && aEle.remove()) || (aEle.removeNode && aEle.removeNode(true));
};
imitateClick('https://www.baidu.com');
适用场景:
- js中直接做无感跳转,但是此方法有个弊端:经过验证,有的浏览器可能会拦截,慎用。
js中window对象location属性跳转
window.location.href = 'https://www.baidu.com';
top.window.location.href = 'https://www.baidu.com';
适用场景:
- window.location.href是覆盖当前页面跳转,在iframe嵌套内页跳转只能改变iframe的src。
- top.window.location.href是覆盖顶层地址跳转,在iframe嵌套内页跳转可以覆盖顶层地址打开新页面,且浏览器无拦截。
js中window对象的open方法跳转
新窗口打开一个链接:
window.open('https://www.baidu.com');
打开一个新的空白窗口(类似弹窗),并指定一些窗口特征,查看更多属性:
window.open('https://m.book118.com','','left=200,top=200,width=200,height=100');
适用场景:
- window.open与top.window.open效果是一样的,都是新窗口打开页面;
- window.open指定窗口特征,可当弹窗使用。
- window.open在iframe中使用会被浏览器拦截。
重定向跳转
当前页面地址重定向:
window.location.replace('https://www.baidu.com');
顶层地址重定向:
top.window.location.replace('https://www.baidu.com');
适用场景:
- window.location.replace()在iframe中使用只是重定向src地址。
- top.window.location.replace()使用效果和top.window.location.href效果一样,可以在iframe中使用,且浏览器无拦截。
meta标签跳转
<meta http-equiv="refresh" content="5;url=http://www.w3school.com.cn">
content="5;url=http://www.w3school.com.cn"中的5代表5秒,url代表跳转地址。
适用场景:
- 适合进入页面直接跳转,这种方式可以作为了解。