常用js方法记录 欢迎私信补充添加,相互学习

这篇博客分享了几个JavaScript的实用函数,包括生成随机颜色、元素滚动到顶部、数组乱序、文件下载以及日期格式处理。此外,还介绍了如何在内容首次出现时添加动画效果,利用getBoundingClientRect实现。
摘要由CSDN通过智能技术生成

生成随机颜色

const generateRandomHexColor = () =>
\`#${Math.floor(Math.random() \* 0xffffff) .toString(16)}\`;

滚动到顶部 滚动的写法 让当前的元素滚动到浏览器窗口的可视区域内

const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" })
//回到页面顶部
document.body.scrollTop = document.documentElement.scrollTop=0;

数组乱序

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)// 测试
const arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\];
console.log(shuffleArray(arr))

下载文件方法记录

//请求方法

export const Generate = (data) => {
return request({
url: '/download',
method: 'post',
data,
responseType: 'blob'
})
}
let data = await Generate ({
fileName: 'userTemplate.xlsx'
})
// 提取文件名
// const fileName = data.headers['content-disposition'].match(
// /filename=(.*)/
// )[1]
const blob = new Blob([data.data], { type: 'application/octet-stream' })
// 创建新的URL并指向File对象或者Blob对象的地址
const blobURL = window.URL.createObjectURL(blob)
// 创建a标签,用于跳转至下载链接
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', '模板.xlsx')
// 兼容:某些浏览器不支持HTML5的download属性
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
// 挂载a标签
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
// 释放blob URL地址
window.URL.revokeObjectURL(blobURL)

处理日期格式

export function parseTime(time: any, pattern: string) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/\//gm), '-')
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }

    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    } as any
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/ig, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str{y}-{m}-{d}
}
//调用方式 
parseTime(new Date(),'{y}-{m}-{d}')

当内容第一次出现时添加动画效果 主要是用了 getBoundingClientRect

window.addEventListener('scroll', function () {
      updateAnimate();
 });
function updateAnimate(){
    let preAnimate = document.querySelectorAll('.pre-animate'),
        animated = document.querySelectorAll('.animated');

    animated = [];

    let bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;

    for(let i = 0,l = preAnimate.length;i<l;i++){
        let cur = preAnimate[i];
        let curRect = cur.getBoundingClientRect();
        if(curRect.top < bodyHeight){
            cur.classList.remove('pre-animate');
            cur.classList.add('animated');
        }
    }

    for(let i = 0,l = animated.length;i<l;i++){
        let cur = animated[i];
        let curRect = cur.getBoundingClientRect();
        if(curRect.top > bodyHeight && cur.classList.contains('animate-once') === false){
            cur.classList.remove('animated');
            cur.classList.add('pre-animate');
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值