判断所有数据类型
@param obj 要判断类型的数据
@return {string} 数据类型(小写)
const type = (function () {
// 映射类型
const classType =
"Boolean Number String Function Array Date RegExp Object Error Null Undefined"
.split(" ")
.reduce((obj, item) => {
obj["[object " + item + "]"] = item.toLowerCase();
return obj;
}, {});
return function (obj) {
// 仅 undefined 与 null 成立
if (obj == null) {
return obj + "";
}
return typeof obj === "object"
? classType[Object.prototype.toString.call(obj)]
: typeof obj;
};
})();
// Examples
console.log(type(new Date())); // date
console.log(type([1, 2])); // array
console.log(type(1)); // number
console.log(type({})); // object
判断空对象
function isEmptyObject(obj) {
if (Object.prototype.toString.call(obj) !== "[object Object]") return false;
var name;
for (name in obj) {
return false;
}
return true;
}
// Examples
console.log(isEmptyObject({})); // true
console.log(isEmptyObject([])); // false
console.log(isEmptyObject(null)); // false
console.log(isEmptyObject(undefined)); // false
console.log(isEmptyObject(1)); // false
console.log(isEmptyObject("")); // false
console.log(isEmptyObject(true)); // false
判断当前运行环境
function userAgent() {
var u = navigator.userAgent;
return {
// 移动终端浏览器版本信息
trident: u.indexOf("Trident") > -1, // IE内核
presto: u.indexOf("Presto") > -1, // opera内核
webKit: u.indexOf("AppleWebKit") > -1, // 苹果、谷歌内核
gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") === -1, // 火狐内核
mobile: !!u.match(/AppleWebKit.Mobile./), // 是否为移动终端
iPad: u.indexOf("iPad") > -1, // 是否iPad
webApp: u.indexOf("Safari") === -1, // 是否web应该程序,没有头部与底部,
isiOS: !!u.match(/(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
isAndroid: u.indexOf("Android") > -1 || u.indexOf("Adr") > -1,
};
}
// Examples
const browser = userAgent();
if (browser.mobile) {
// 移动端 => todo something
if (browser.isiOS && browser.webApp) {
// IOS系统 && web程序 => todo something
} else {
// 安卓 => todo something
}
} else {
// PC => todo something
}
平滑滚动到页面顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// Examples
scrollToTop();
将视口平滑滚动到指定元素
const smoothScroll = (element) =>
document.querySelector(element).scrollIntoView({
behavior: "smooth",
});
// Examples
smoothScroll("#fooBar");
监听滚动结束
const onScrollStop = (callback) => {
let isScrolling;
window.addEventListener(
"scroll",
(e) => {
clearTimeout(isScrolling);
isScrolling = setTimeout(() => {
callback();
}, 150);
},
false
);
};
// Examples
onScrollStop(() => {
console.log("The user has stopped scrolling");
});
监听点击指定元素外部
const onClickOutside = (element, callback) => {
document.addEventListener("click", (e) => {
if (!element.contains(e.target)) callback();
});
};
// Examples
onClickOutside("#my-element", () => console.log("Hello"));
获取浏览器当前语言
// defaultLang 为默认语言
const detectLanguage = (defaultLang = "en-US") =>
navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
defaultLang;
// Examples
detectLanguage(); // 'nl-NL'
控制浏览器全屏、退出全屏
const fullscreen = (mode = true, el = "body") =>
mode
? document.querySelector(el).requestFullscreen()
: document.exitFullscreen();
// Examples
fullscreen(); // Opens body
in fullscreen mode
fullscreen(false); // Exits fullscreen mode
封装原生 GET、POST 请求
const httpGet = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send();
};
const httpPost = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/json; charset=utf-8");
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send(data);
};
// Examples
httpGet("", console.log); /
Logs: {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
} /
httpPost(
"http://www.zidongmutanji.com/bxxx/172484.html
",
null, // does not send a body
console.log
); /
Logs: {
"id": 101
} /