自定义工具函数
(function() {
let myTool = {
$: function(id) {
return typeof id === "string" ? document.getElementById(id) : null
},
screenClient: function() {
if (window.innerWidth != null) {
return {
width: window.innerWidth,
height: window.innerHeight
}
} else if (document.compatMode === "CSS1Compat") {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
} else {
return {
width: document.body.clientWidth,
height: document.body.clientHeight
}
}
},
scroll: function() {
if (window.pageYOffset !== null) {
return {
top: window.pageYOffset,
left: window.pageXOffset
}
} else if (document.compatMode === "CSS1Compact") {
return {
top: document.documentElement.scrollTop,
left: document.documentElement.scrollLeft
}
} else {
return {
top: document.body.scrollTop,
left: document.body.scrollLeft
}
}
},
//获取css值
getStyle(obj, attr) {
if (obj.currentStyle) { //IE opera
return obj.currentStyle[attr]
} else {
return document.defaultView.getComputedStyle(obj, null)[attr]
}
},
setStyle(obj, attr, val) {
obj.style[attr] = val
},
//缓动动画函数
buffer(obj, attr, target, cb) {
clearInterval(obj.timer)
let begin = 0
obj.timer = setInterval(() => {
// 求出步长
/* let speed=(target-obj.offsetLeft)*0.2*/
if (attr === "scrollTop") {
begin = obj.scrollTop
} else {
begin = this.getStyle(obj, attr)
begin = parseInt(begin)
}
let speed = (target - begin) * 0.2
//判断向上或向下取整
speed = target > begin ? Math.ceil(speed) : Math.floor(speed)
if (attr === "scrollTop") {
obj.scrollTop = begin + speed
} else {
obj.style[attr] = begin + speed + "px"
}
//判断
//console.log(begin,target)
if (begin === target) {
clearInterval(obj.timer)
if (cb) {
cb()
}
}
//移动
// obj.innerText=begin
}, 20)
},
buffers(obj, json, cb) {
clearInterval(obj.timer)
let begin = 0
let target = 0
let speed = 0
let flag = true
obj.timer = setInterval(() => {
for (let key in json) {
if (key === "scrollTop") {
begin = obj.scrollTop
target = parseInt(json[key])
} else {
begin = parseInt(this.getStyle(obj, key)) || 0
target = parseInt(json[key])
}
speed = (target - begin) * 0.2
speed = target > begin ? Math.ceil(speed) : Math.floor(speed);
if (key === "scrollTop") {
obj.scrollTop = begin + speed
} else {
obj.style[key] = begin + speed + "px"
}
console.log(begin, target)
if (begin === target) {
flag = false
}
}
// console.log(flag);
if (flag) {
clearInterval(obj.timer)
if (cb) {
cb()
}
}
}, 20)
},
//栈的构造函数
Stack: function() {
//栈的属性
this.items = []
//栈的相关操作
//1.将元素压入栈
this.push = function(ele) {
this.items.push(ele)
}
//2.将元素移出栈
this.pop = function() {
return this.items.pop()
}
//3.查看栈顶元素
this.peek = function() {
return this.items[this.items.length - 1]
}
//4.判断栈是否为空
this.isEmpty = function() {
return this.items.length === 0
}
//5.求栈的个数
this.size = function() {
return this.items.length
}
//6.转化成字符串
this.toStr = function() {
let str = ""
for (let i = 0; i < this.items.length; i++) {
str += this.items[i] + ""
}
return str
}
},
//队列的构造函数
Queue: function() {
this.items = []
//1.元素加入到队列
this.enqueue = function(element) {
this.items.push(element)
}
//2.删除队列的前端元素
this.delqueue = function() {
return this.items.shift()
}
//3.查看队列的前端元素
this.front = function() {
return this.items[this.items.length - 1]
}
//4.队列是否为空
this.isEmpty = function() {
return this.items.length === 0
}
//5.查看队列元素个数
this.size = function() {
return this.items.length
}
//6.toString
this.toString = function() {
let str = ""
for (let i = 0; i < this.items.length; i++) {
str += this.items[i] + ""
}
return str
}
},
//优先级队列
PriorityQueue: function() {
//数字越小,优先级越大
function Priority(ele, priority) {
this.element = ele
this.priority = priority
}
this.items = []
//插入元素
this.enqueue = function(element, priority) {
let queueElement = new Priority(element, priority)
let added = false
if (this.items.length === 0) {
this.items.push(queueElement)
} else {
for (let i = 0; i < this.items.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement)
added = true
break
}
}
if (!added) {
this.items.push(queueElement)
}
}
}
//2.删除队列的前端元素
this.delqueue = function() {
return this.items.shift()
}
//3.查看队列的前端元素
this.front = function() {
return this.items[this.items.length - 1]
}
//4.队列是否为空
this.isEmpty = function() {
return this.items.length === 0
}
//5.查看队列元素个数
this.size = function() {
return this.items.length
}
//6.toString
this.toString = function() {
let str = ""
for (let i = 0; i < this.items.length; i++) {
str += this.items[i].element + ""
}
return str
}
},
//十进制转二进制
decToBin(decNum) {
let s = new this.Stack()
while (decNum > 0) {
//获取余数,放入栈中
s.push(decNum % 2)
//获取整除后的结果,作下一次运算
decNum = Math.floor(decNum / 2)
}
//从栈中取出值
let binaryStr = ""
while (!s.isEmpty()) {
binaryStr += s.pop()
}
return binaryStr
},
//击鼓传花
passGame(nameList, num) {
// 1.创建队列结果
let q = new myTool.Queue()
// 2.所有人依次加入队列
for (let i = 0; i < nameList.length; i++) {
q.enqueue(nameList[i])
}
//3.开始数数字
while (q.size() > 1) {
//不是num,重新加入到队列末尾
//是num时,将其从队列里删除,num之前的人重新加入到队列末尾
for (let i = 0; i < num - 1; i++) {
q.enqueue(q.delqueue())
}
//这时队列第一个就是num对应的人,直接从队列删除
q.delqueue()
}
//4.获取剩下的那个人
let endName = q.front()
return nameList.indexOf(endName)
},
//url参数转对象
getUrlParams(url) {
let index = url.indexOf("?")
let params = url.substr(index + 1)
let paramsArr = params.split("&")
let obj = {}
paramsArr.forEach((value) => {
let tempArr = value.split("=")
let key = tempArr[0]
obj[key] = tempArr[1]
})
return obj
},
//九宫格布局
j_flex(allCols, parentNode) {
let box = parentNode.children[0]
//获取子元素宽高
var boxw = box.offsetWidth
var boxh = box.offsetHeight
var marginxy = 15
//遍历子元素
for (let i = 0; i < parentNode.children.length; i++) {
//求出当前盒子所在的行和列
let row = Math.floor(i / allCols)
let col = Math.floor(i % allCols)
//当前盒子的定位
let currentbox = parentNode.children[i]
currentbox.style.position = "absolute"
currentbox.style.left = col * (boxw + marginxy) + "px"
currentbox.style.top = row * (boxh + marginxy) + "px"
}
},
//瀑布流布局
/**
* 实现瀑布流布局
* @param parent {string} id选择器
* @param child {string} 类选择器
*/
waterFull(parent, child) {
//瀑布流,等宽不等高
var father = document.getElementById(parent)
var allBox = father.getElementsByClassName(child)
father.style.position = "relative"
//子盒子css要设置浮动
//获取其中一个子盒子宽度
var boxWidth = allBox[0].offsetWidth
//获取文档宽度
var screenWidth = document.documentElement.clientWidth || document.body.clientWidth
//求出列数
var cols = parseInt(screenWidth / boxWidth)
//求出父盒子宽度并居中
father.style.width = cols * boxWidth + "px"
father.style.margin = "0 auto"
//子盒子定位
var heightArr = []
var boxHeight = 0
var minboxHeight = 0
var minIndex = 0
//遍历所有盒子
for (var i = 0; i < allBox.length; i++) {
boxHeight = allBox[i].offsetHeight
//判断盒子是否属于第一行
if (i < cols) {
heightArr.push(boxHeight)
} else {
//求出数组中最矮的盒子
minboxHeight = Math.min(...heightArr)
console.log(heightArr);
console.log(minboxHeight);
//求出最矮盒子的索引
minIndex = heightArr.indexOf(minboxHeight)
console.log(minIndex);
//剩余盒子定位
allBox[i].style.position = 'absolute'
allBox[i].style.left = boxWidth * minIndex + "px"
allBox[i].style.top = minboxHeight + "px"
//更新最小高度
heightArr[minIndex] += boxHeight
console.log(1111, heightArr);
}
}
},
//时间格式化
/**
* @param date {Date}
* @param fmt {string} yy-mm-dd
*/
formatDate(date, fmt) {
if (!(date instanceof Date)) {
throw "date必须为Date对象"
}
if (typeof fmt != "string") {
throw "fmt必须为String"
}
let padLeftStr = function(str) {
return ('00' + str).substr(str.length)
}
//获取年份
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
}
//获取月,日,时,分钟,秒
var obj = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds()
}
for (let k in obj) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = obj[k] + ""
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? str : padLeftStr(str))
}
}
return fmt
},
//创建验证码
createCode() {
let code = ""
let codelength = 4
let randCode = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'H', 'I', 'J', 'K', 'L', 'M', 'N'
]
for (let i = 0; i < codelength; i++) {
//设置随机范围
let index = Math.floor(Math.random() * randCode.length)
code += randCode[index]
}
return code
},
//获取min和max之间的整数
/**
* @param min {number}
* @param max {number}
* @return {number}
*/
random(min, max) {
return Math.floor(Math.random() * (max - min) + min)
},
//获取随机颜色 rgb(0-255,0-255,0-255)
randomColor() {
var r = Math.random(0, 256)
var g = Math.random(0, 256)
var b = Math.random(0, 256)
var result = `r${r}g${g}b${b}`
return result
},
/**
* 深拷贝
* @param {object}fromObj 拷贝的对象
* @param {object}toObj 目标对象
*/
deepCopy(fromObj, toObj) {
/**
* 辅助函数, 判断是否是对象
* @param {object}obj
* @returns {boolean}
*/
function isObj(obj) {
return obj instanceof Object;
}
for (var key in fromObj) {
// 1. 取出键值对
var fromValue = fromObj[key];
// 2. 检查当前的属性值是什么类型
if (!isObj(fromValue)) { // 如果是值类型,那么就直接拷贝赋值
toObj[key] = fromValue;
} else {
// 如果是引用类型,
// 那么就再调用一次这个方法,
// 去内部拷贝这个对象的所有属性
var tempObj = new fromValue.constructor;
console.log(fromValue.constructor === Object);
deepCopy(fromValue, tempObj);
toObj[key] = tempObj;
}
}
},
/**
* 数组去重1
* @param {Array} array
* @return {Array}
*/
unique1(array) {
// 1. 定义数组
var temp = [];
// 2. 遍历当前数组
for (var i = 0; i < array.length; i++) {
// 3.如果当前数组的第i已经保存进了临时数组,
// 那么跳过,否则把当前项push到临时数组里面
if (-1 === temp.indexOf(this[i])) {
temp.push(array[i]);
}
}
return temp;
},
/**
* 数组去重2
* @param {Array} array
*/
unique2(array) {
var unique = [...new Set(array)];
return unique
},
/**
*判断一个对象是否为数组
* @param arg
* @return {boolean}
*/
isArray(arg) {
if (typeof arg === 'object') {
return Object.prototype.toString.call(arg) === '[object Array]';
}
return false;
},
/**
* 实现数组的随机排序1
* @param {Array} arr
*/
randSort1(arr) {
for (var i = 0, len = arr.length; i < len; i++) {
var rand = parseInt(Math.random() * len);
var temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
return arr;
},
/**
* 实现数组的随机排序2
* @param {Array} arr
*/
randSort2(arr) {
var mixedArray = [];
while (arr.length > 0) {
var randomIndex = parseInt(Math.random() * arr.length);
mixedArray.push(arr[randomIndex]);
arr.splice(randomIndex, 1);
}
return mixedArray;
},
}
window.myTool = myTool
})()
若有仙鹤从旁骥,尽是人间第一流。