一、获取元素的现有样式
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);