大家好、这里给大家分享一些工作中能用到的业务代码实现。
包你好用
文件上传
<form id="file-upload-form">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
const form = document.querySelector('#file-upload-form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log('上传成功');
}
};
xhr.send(formData);
});
文件下载
const fileUrl = 'https://example.com/myfile.pdf';
// 发送HTTP GET请求获取文件内容
fetch(fileUrl)
.then(response => response.blob()) // 将文件内容转换为blob对象
.then(blob => {
// 创建一个URL对象,用于生成下载链接
const url = URL.createObjectURL(blob);
// 创建一个<a>元素并设置其href属性为要下载的文件URL
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = 'myfile.pdf'; // 设置下载文件的名称
// 将<a>元素添加到文档中,并模拟点击以开始下载
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
表格导出Excel
借助第三方库xlsx.js
function exportExcel(tableEl,name){
var wb = XLSX.utils.table_to_book(tableEl, { sheet: "Sheet JS" });
return XLSX.writeFile(wb, name);
}
// use
exportExcel(document.querySelector('table'),'file.xlsx')
图片文字反色
<div class="container">
<div class="text-overlay">
<h1>Hello World</h1>
</div>
</div>
.container {
background-image: url('https://www.bing.com/th?id=OHR.HippoDayChobe_ZH-CN2883647954_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&qlt=50');
background-size: cover;
height: 500px;
width: 100%;
}
.text-overlay {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
mix-blend-mode: difference;
color: white;
font-size: 3em;
}
预览:
毛玻璃
方案1(blur)
.blur {
background-image: url("your-image.jpg");
width: 100%;
height: 100%;
position: relative;
}
.blur::before {
content: "";
background-image: url("your-image.jpg");
filter: blur(10px);
position: absolute;
top: -10px;
bottom: -10px;
left: -10px;
right: -10px;
z-index: -1;
}
方案2(backdrop-filter)
.container {
background-image: url('your-image.jpg');
width: 100%;
height: 100%;
position: relative;
}
.blur {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
backdrop-filter: blur(5px);
}
数字千位分隔符
const number = 1234567.89;
const formattedNumber = number.toLocaleString();
console.log(formattedNumber); // 输出 "1,234,567.89"
日期格式化yyyy-mm-dd
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
console.log(formattedDate); // 例如:2023-02-15
字符串按拼音排序
// 原始字符串数组
const strArr = ['张三', '李四', '王五', '赵六', '钱七']
// 使用 Intl.Collator 对象进行排序
const collator = new Intl.Collator('zh', {sensitivity: 'base'})
strArr.sort(collator.compare)
// 排序后的字符串数组
console.log(strArr) //['李四', '钱七', '王五', '张三', '赵六']