JS方法扩展,扩展ing

一、获取元素的现有样式

HTMLElement.prototype.getStyle = function(key){
    return window.getComputedStyle(this,null)[key];
}

二、回到顶部

window.scrollTop = function(time){
    let timer = setInterval(()=>{
        if(document.documentElement.scrollTop < 1){
            document.documentElement.scrollTop = 0;
            clearInterval(timer);
        }
        document.documentElement.scrollTop *= 0.8;
    }, time || 20);
}


三、优化了的scroll滚动事件

window.scrollListener = function(fn,time){
    let timer;
    window.addEventListener('scroll',()=>{
        clearTimeout(timer);
        timer = setTimeout(()=>{
            fn();
        }, time || 100);
    });
}

 

 

简单地仿PHP date()方法,返回特定格式的日期和时间。

window.date = function(format = 'Y-m-d H:i:s',timestamp = false){
    let now = new Date();
    if(timestamp){
        if(timestamp.toString().length === 13){
            now.setTime(timestamp);	
        }else{
            console.log('时间戳应该为毫秒');
            return false;
        }
    }
    let str = '',i = 0,w;
    while(w = format.charAt(i++)){
        switch(w){
            case 'Y':
                str += now.getFullYear();
                break;
            case 'm':
                str += pad0(now.getMonth() + 1);
                break;
            case 'd':
                str += pad0(now.getDate());
                break;
            case 'H':
                str += pad0(now.getHours());
                break;
            case 'i':
                str += pad0(now.getMinutes());
                break;
            case 's':
                str += pad0(now.getSeconds());
                break;
            default:
                str += w;
        }
    }
    return str;
}
function pad0(value){
    return value > 9 ? value : '0' + value;
}

删除数组中指定的值

Array.prototype.deleteValue = function(value){
    let index = this.indexOf(value);
    return index > -1 ? this.splice(index,1) : false;
}

数组去重两个方法

Array.prototype.unique1 = function(){
    let arr = [],obj = {};
    for (let i of this) {
        if(obj[i] === undefined){
            arr.push(i);
            obj[i] = true;
        }
    }
    return arr;
}
Array.prototype.unique2 = function(){
    return Array.from(new Set(this));
}

 

类型转换

//对象键名转数组
Object.keys(obj);
//对象键值专属组
Object.values(obj);
//对象转JSON
JSON.stringify(obj);
//JSON转对象
JSON.parse(str);
//Set转数组
Array.from(set);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值