页面跳转
a 标签
<a href='www.baidu.com' target='_self'>百度一下,你就知道</a>
<!--href='#maodian' 时点击滚动到当前页面 id=maodian 的元素上-->
- _blank 新窗口打开
- _parent 父级窗口打开(iframe)
- _self 当前窗口打开(默认)
- _top 顶级窗口打开(iframe)
- framename 窗口的名字,替换指定窗口
window.open
window.open('http://www.baidu.com') // 默认没有名字另起一个页签
window.open('http://www.baidu.com', 'new-name') // 名字相同打开相同的页签,不同打开不同的页签
window.open('http://www.baidu.com', '_self') //在当前页面打开新页面
window.open('http://www.baidu.com', '_top')
window.open('http://www.baidu.com', '_parent')
location.href
location.href='http://www.baidu.com' // 默认在当前页面打开新页面
this.location.href='http://www.baidu.com' // 当前页面打开
top.location.href='http://www.baidu.com'
parent.location.href='http://www.baidu.com'
self.location.href='http://www.baidu.com' // 当前页面打开
window.location.href = window.location.href // 刷新当前页面
location.reload() // 刷新当前页面
下载
// js 创建 a 标签打开新页面或执行下载
const a = document.createElement('a', filename)
a.style.display = 'none'
a.href = 'xxx'
a.target = '_blank'
if(filename) {
a.setAttribute('download', filename) //设置下载属性 以及文件名
}
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
对于批量下载的场景,可以使用动态创建 iframe 的方式下载,浏览器不会闪烁。
downloadFile(url) {
try {
let ele = document.createElement('iframe');
ele.src = url;
ele.style.display = 'none';
document.body.appendChild(ele);
//防止下载2次
setTimeout(function () {
document.body.removeChild(ele)
}, 1000);
} catch(e) {
console.error(e);
}
}