http://zhuang.leesioisme.top/useful-functions
实用性函数-项目地址
01.实用性函数 —— 计算日期间隔
const getDateTimeInterval = (dateStart, dateEnd) => {
const timeInterval = dateStart > dateEnd ? new Date(dateStart) - new Date(dateEnd) : new Date(dateEnd) - new Date(dateStart);
return timeInterval / (1000 * 60 * 60 * 24);
}
02.实用性函数 —— 等待指定时间后调用函数
const delay = (cb, time, ...args) => {
setTimeout(cb, time, args)
console.log("delay time: ", time)
}
delay(text => { console.log("output for a while:", ...text) }, 1000, "text", "data", "game", "password")
03.实用性函数 —— 判断当前是移动设备还是桌面设备
const checkDevice = () => {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop"
}
const deviceName = checkDevice();
04.实用性函数 —— 确认父元素是否包含子元素
const hasChild = (parent, child) => parent !== child && parent.contains(child);
05.实用性函数 —— 如何将一组表单元素编码为一个对象
const getFormData = (form) => {
const formData = [...new FormData(form)]
return formData.reduce((prev, [key, value]) => ({ ...prev, [key]: value }), {})
}
const formData = getFormData(document.querySelector("#loginForm"));
06.实用性函数 —— 是否含有某个类
const hasClass = (el, className) => {
let span = document.querySelector("span");
[...el].forEach((v, i) => {
span.innerHTML += `第${i + 1}个p,是否包含${className}: ${v.classList.contains(className)} </br>`
})
}
hasClass(document.querySelectorAll(".box p"), "paragraph")
07.实用性函数 —— 元素在视口是否可见
const elementIsVisiableInViewport = (el, partiallyVisiable = false) => {
const { top, right, bottom, left } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisiable ?
((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight))
&&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
:
(top >= 0 && right <= innerWidth && bottom >= 0 && left >= 0)
}
08.实用性函数 —— 获取元素内所有图像
const getAllImg = (el, includeDuplicates = false) => {
const images = [...el.querySelectorAll("img")].map(img => img.getAttribute("src"));
return includeDuplicates ? images : [...new Set(images)]
}
09.实用性函数 —— 获取当前URL
// 获取当前url
const getCurrentUrl = () => window.location.href;
const currentUrl = getCurrentUrl();
// 获取指定url的查询字符串对象
document.querySelector("#result").innerHTML = currentUrl;
const getUrlQueryString = (url) => url.match(/([^?=&]+)(=([^&]*))/g || []).reduce(
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a),
{}
)
const queryString = getUrlQueryString("http://blog.leesioieme.top/users?_i=DxaSAD23hSA2sD&_n=123456789&_d=true")
10.实用性函数 —— 获取可读的毫秒数
var input = document.querySelector("#input")
var output = document.querySelector("#output")
const formatSeconds = ms => {
ms = ms < 0 ? -ms : ms;
const time = {
day: Math.floor(ms / (1000 * 60 * 60 * 24)),
hour: Math.floor(ms / (1000 * 60 * 60)) % 24,
minute: Math.floor(ms / (1000 * 60)) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
}
const timeEntries = Object.entries(time).filter(v => v[1] > 0).reduce((prev, curr) => (prev + " " + curr[1] + " " + (curr[1] > 1 ? curr[0] + "s " : curr[0] + " ")), "")
return timeEntries;
}
11.实用性函数 —— 获取当前页面鼠标滚动位置
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
const getCurrentScrollPosition = (e = window) => ({
x: e.pageXOffset ? e.pageXOffset : e.scrollX || 0,
y: e.pageYOffset ? e.pageYOffset : e.scrollY || 0
})
const setCurrentScrollPosition = () => {
let position = getCurrentScrollPosition();
document.querySelector("#scrollPosition").innerHTML = position.x + ", " + position.y
}
12.实用性函数 —— 从对象中筛选出指定指示器的属性值
const get = (source, ...selectors) => [...selectors].map(v => v.replace(/\[([^\[\]]*)\]/g, ".$1.").split(".").filter(t => t !== "").reduce((prev, curr) => prev && prev[curr], source))
const obj = {
name: "Utility Function",
madeby: "DaZhuang Li",
description: {
name: "get",
params: [
{
name: "source",
type: ["array", "object"],
remark: "This params require an Object or Array"
},
{
name: "selectors",
type: ["String"],
remark: "Multiple selectors"
},
],
code: `get = (source, ...selectors) => [...selectors].map(v => v.replace(/\[([^\[\]]*)\]/g, ".$1.").split(".").filter(t => t !== "").reduce((prev, curr) => prev && prev[curr], source))`,
example: `
const selectObj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
get(selectObj, 'selector.to.val', 'target[0]', 'target[2].a', 'target[].a');
`
},
createTime: "2020-10-26 09:20 AM"
}
const result = get(obj, "name", "description[name]", "description.params", "params[].remark")
13.实用性函数 —— 隐藏所有元素
const toggleHide = (el) => [...el].forEach(v => (v.style.display = v.style.display == "none" ? "block" : "none"))
const hidePTag = () => toggleHide(document.querySelectorAll(".box p"))
14.实用性函数 —— 移除元素的时间侦听器
const handler = function (e = window) { console.log(this) };
var wrapper = document.querySelector("#wrapper")
var middle = document.querySelector("#middle")
var inner = document.querySelector("#inner")
wrapper.addEventListener("click", handler, true)
middle.addEventListener("click", handler, true)
inner.addEventListener("click", handler, true)
const offEvent = (el, event, fn, option = false) => el.removeEventListener(event, fn, option)
offEvent(wrapper, "click", handler, true);
15.实用性函数 —— 切换元素类
const toggle = (el, className) => [...el].forEach(v => v.classList.toggle(className))
const toggleClass = () => toggle(document.querySelectorAll("p"), "paragraph");
16.实用性函数 —— 对传递的URL进行GET请求
const getRequest = (url, cb, err = console.error) => {
const request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = res => {
var resData = res.target.responseText && JSON.parse(res.target.responseText)
cb(resData)
}
request.onerror = error => {
err(error)
};
request.send();
}
getRequest('https://jsonplaceholder.typicode.com/posts/1', console.log);
17.实用性函数 —— 对传递的URL进行POST请求
const postRequest = (url, data, cb, err = console.error) => {
const request = new XMLHttpRequest();
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json, charset=utf-8")
request.onload = () => cb(request.responseText)
request.onerror = () => err(request)
request.send(data);
}
const postData = {
name: "DaZhuang Li",
age: 23,
sex: "M"
}
postRequest('https://jsonplaceholder.typicode.com/posts', JSON.stringify(postData), console.log);