常用js封装方法,持续更新
Posted STRIVE_LC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用js封装方法,持续更新相关的知识,希望对你有一定的参考价值。
// 数组去重
function unique1(arr) {
return […new Set(arr)]
}
function unique2(arr) {
var obj = {};
return arr.filter(ele => {
if (!obj[ele]) {
obj[ele] = true;
return true;
}
})
}
function unique3(arr) {
var result = [];
arr.forEach(ele => {
if (result.indexOf(ele) == -1) {
result.push(ele)
}
})
return result;
}
// 数据类型
function whichType(value) {
return Object.prototype.toString.call(value)
}
console.log(Object.prototype.toString.call('xxx')); //'[object String]'
console.log(Object.prototype.toString.call(12)); //'[object Number]'
console.log(Object.prototype.toString.call(true)); //'[object Boolean]'
console.log(Object.prototype.toString.call(undefined)); //'[object Undefined]'
console.log(Object.prototype.toString.call(null)); //'[object Null]'
console.log(Object.prototype.toString.call({name: "licong"})); //'[object Object]'
console.log(Object.prototype.toString.call(function(){})); //'[object Function]'
console.log(Object.prototype.toString.call([])); //'[object Array]'
console.log(Object.prototype.toString.call(new Date)); //'[object Date]'
console.log(Object.prototype.toString.call(/\\d/)); //'[object RegExp]'
// 深拷贝
function deepClone(obj, result) {
var result = result || {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] == "object" && obj[prop] !== null) {
// 引用值(obj/array)且不为null
if (Object.prototype.toString.call(obj[prop]) == "[object Object]") {
// 对象
result[prop] = {};
} else {
// 数组
result[prop] = [];
}
deepClone(obj[prop], result[prop]);
} else {
// 原始值或func
result[prop] = obj[prop];
}
}
}
return result;
}
// 判断元素有没有子元素
function hasChildren(e) {
var children = e.childNodes,
len = children.length;
for (var i = 0; i < len; i++) {
if (children[i].nodeType === 1) {
return true;
}
}
return false;
}
// 一个元素插入到另一个元素的后面
Element.prototype.insertAfter = function (target, elen) {
var nextElen = elen.nextElenmentSibling;
if (nextElen == null) {
this.appendChild(target);
} else {
this.insertBefore(target, nextElen);
}
};
// 获得滚动条的滚动距离
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset,
};
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop,
};
}
}
// 获取任一元素的任意属性
function getStyle(elem, prop) {
return window.getComputedStyle
? window.getComputedStyle(elem, null)[prop]
: elem.currentStyle[prop];
}
// 绑定事件的兼容代码
function addEvent(elem, type, handle) {
if (elem.addEventListener) {
//非ie和非ie9
elem.addEventListener(type, handle, false);
} else if (elem.attachEvent) {
//ie6到ie8
elem.attachEvent("on" + type, function () {
handle.call(elem);
});
} else {
elem["on" + type] = handle;
}
}
// 解绑事件
function removeEvent(elem, type, handle) {
if (elem.removeEventListener) {
//非ie和非ie9
elem.removeEventListener(type, handle, false);
} else if (elem.detachEvent) {
//ie6到ie8
elem.detachEvent("on" + type, handle);
} else {
elem["on" + type] = null;
}
}
// 取消冒泡的兼容代码
function stopBubble(e) {
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
// 获取地址栏参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
function getParams(url) => {
const keyValueArr = url.split('?')[1].split('&')
let paramObj = {}
keyValueArr.forEach(item => {
const keyValue = item.split('=')
paramObj[keyValue[0]] = keyValue[1]
})
return paramObj
}
// 是否是移动端设备
function isMobile() {
return navigator.userAgent.match(/(iPhone|iPod|android|ios)/i)
}
// 防抖函数
function debounce(fn, delay) {
var timer = null
return function () {
var context = this
var args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(context, args)
}, delay)
}
}
// 计算相隔天数
function calDay(timestamp) => {
if (!timestamp) {
return 0
}
const now = new Date().getTime() / 1000
return parseInt((now - timestamp) / 60 / 60 / 24)
}
// 电话号码脱敏处理
function phoneDesensitization(phone) => {
return phone.replace(/(\\d{3})\\d*(\\d{4})/, '$1****$2')
}
// 校验手机号格式
function varifyPhoneNumber(phone) => {
return /^1\\d{10}$/.test(phone)
}
// 数组对象中相同的id进行分类
function classify(list) {
let newData = {}
list.forEach(item => {
if (Object.keys(newData).indexOf('' + item.id) === -1) {
newData[item.id] = []
}
newData[item.id].push(item)
})
return newData
// [{id:'1',title: '123'},{id: '1',title: '456'},{id: '2', title: '789'}]
// {1: [{id: '1', title: '123'},{id: '1', title: '456'}], 2: [{id: '2', title: '789'}]}
}
// 金额字段格式化
function moneyFormat(value) {
if (value) {
const nums = value.toString().split('.');
if (nums[0]) {
nums[0] = nums[0].replace(/,/g, '');
const re = /(?=(?!(\\b))(\\d{3})+$)/g;
nums[0] = nums[0].replace(re, ',');
}
if (nums[1]) {
nums[1] = nums[1].substr(0, 4);
} else {
nums[1] = '00';
}
return `${nums[0]}.${nums[1]}`;
} else {
return '';
}
}
// 判断是否是邮箱格式
function isEmail(str) {
var reg = /^[a-zA-Z0-9]+([._-]*[a-zA-Z0-9]*)*@[a-zA-Z0-9]+.[a-zA-Z0-9{2,5}$]/;
var result = reg.test(str);
return result
}
// 设置cookie值
function setCookie(name, value, Hours) {
var d = new Date();
var offset = 8;
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var nd = utc + (3600000 * offset);
var exp = new Date(nd);
exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;"
}
// 获取cookie值
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return unescape(arr[2]);
return null
}
// 加入收藏夹
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle)
} catch(e) {
try {
window.sidebar.addPanel(sTitle, sURL, "")
} catch(e) {
alert("加入收藏失败,请使用Ctrl+D进行添加")
}
}
}
// 设为首页
function setHomepage() {
if (document.all) {
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage('http://***')
} else if (window.sidebar) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
} catch(e) {
alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true")
}
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage', 'http://***')
}
}
// 加载样式文件
function LoadStyle(url) {
try {
document.createStyleSheet(url)
} catch(e) {
var cssLink = document.createElement('link');
cssLink.rel = 'stylesheet';
cssLink.type = 'text/css';
cssLink.href = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(cssLink)
}
}
// 获取页面可视高度
function getPageViewHeight() {
var d = document, a = d.compatMode == "BackCompat"
? d.body
: d.documentElement;
return a.clientHeight;
}
以上是关于常用js封装方法,持续更新的主要内容,如果未能解决你的问题,请参考以下文章
前端Util.js-ES6实现的常用100多个javaScript简短函数封装合集(持续更新中)
step by step教你常用JS方法封装 [ 大杂烩 ]