前言
前端人员在开发时经常会遇到:
- 后端给一个地址,需要去下载的需求。
- 将页面的内容复制到剪切板
下载文件
我们先说下载文件,通常情况下我们会自己写上一个非常简单的工具函数。 思路如下:
- 创建一个
a
元素 - 设置a元素跳转的链接,以及下载的文件名
- 将
a
元素添加到页面 - 模拟点击a元素
- 移除
a
元素
js
/**
* 通过url下载文件
* @param {*} url 下载的地址
* @param {*} fileName 下载的文件名,需自行指定后缀
*/
export const downloadByUrl = (url, fileName) => {
const link = document.createElement('a');
link.href = url;
link.download = fileName || '下载文件';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
以上将后端返回的链接地址传进来就可以了,支持blob返回流。
复制到剪切板
通常剪切板的复制用于这种情况,像某个网站,禁止了用户使用鼠标或者ctrl + c
来进行复制时候,在页面给一个复制按钮,让用户手动点击复制。
思路:
- 我们通常使用window的
navigator.clipboard
对象来进行。clipboard
下有一个API--writeText()
,可以将内容复制到clipboard剪切板中。 - 但是有的浏览器比较老旧,不支持
clipboard
对象,我们就得换一种兼容的方法,使用textarea
来模拟,具体的看代码吧~
js
/**
* 复制到剪切板
* @param {*} content 要复制的文本
*/
export const copyToClipboard = (content) => {
/* 复制剪切板的更推荐项目内置的clipboard.js插件,这种方法对浏览器版本要求比较高 */
if (!content) {
return ElMessage({
message: '没有要复制的内容!',
grouping: true,
type: 'error',
})
}
// 浏览器兼容性判断
if (navigator.clipboard) {
navigator.clipboard.writeText(content).then(() => {
ElMessage({
message: '复制成功!',
grouping: true,
type: 'success',
})
})
} else {
// 旧版浏览器兼容方案
const textArea = document.createElement('textarea')
textArea.value = content
textArea.style.position = 'fixed'
// 使临时创建的元素不可见
textArea.style.position = 'fixed';
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = '0';
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
// 复制
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
// 判断是否复制成功
try {
const successful = document.execCommand('copy');
if (successful) {
ElMessage({
message: '复制成功!',
grouping: true,
type: 'success',
})
}
} catch (err) {
ElMessage({
message: '复制失败!',
grouping: true,
type: 'error',
})
}
}
}
好了,今天的分享就结束啦~
朋友,我是喝西瓜汁的兔叽,感谢您的阅读,衷心祝福您和家人身体健康,事事顺心。