/*
|
* @Author: 丘骏_jun
|
* @Date: 2019-11-21 10:59:17
|
* @Last Modified by: 丘骏_jun
|
* @Last Modified time: 2019-12-30 16:29:45
|
*/
|
// 通用function,通过全局安装,或import引用调用
|
|
var fn_obj = {}// fn.js对象
|
|
let scrollBarWidth // 滚动条宽度
|
// 获取浏览器滚动条宽度
|
function getScrollBarWidth() {
|
if (scrollBarWidth !== undefined) return scrollBarWidth
|
|
const outer = document.createElement('div')
|
outer.className = 'el-scrollbar__wrap'
|
outer.style.visibility = 'hidden'
|
outer.style.width = '100px'
|
outer.style.position = 'absolute'
|
outer.style.top = '-9999px'
|
document.body.appendChild(outer)
|
|
const widthNoScroll = outer.offsetWidth
|
outer.style.overflow = 'scroll'
|
|
const inner = document.createElement('div')
|
inner.style.width = '100%'
|
outer.appendChild(inner)
|
|
const widthWithScroll = inner.offsetWidth
|
outer.parentNode.removeChild(outer)
|
scrollBarWidth = widthNoScroll - widthWithScroll
|
|
return scrollBarWidth
|
}
|
// 获取最近样式
|
// function getCurrentStyle (obj, prop) {
|
// if (obj.currentStyle) {
|
// return obj.currentStyle[prop];
|
// } else if (window.getComputedStyle) {
|
// prop = prop.replace(/([A-Z])/g, "-$1");
|
// prop = prop.toLowerCase();
|
// return document.defaultView.getComputedStyle(obj, null)[prop];
|
// }
|
// return null;
|
// }
|
// // 判断是否有滚动条
|
// function hasScrollBar (obj) {
|
// return getCurrentStyle(obj, 'overflow') == 'hidden'
|
// ? 0
|
// : document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight);
|
// }
|
|
// 日期格式化
|
// eslint-disable-next-line no-extend-native
|
Date.prototype.format = function(format) {
|
var o = {
|
'M+': this.getMonth() + 1, // month
|
'd+': this.getDate(), // day
|
'H+': this.getHours(), // hour
|
'm+': this.getMinutes(), // minute
|
's+': this.getSeconds(), // second
|
'q+': Math.floor((this.getMonth() + 3) / 3), // quarter
|
'S': this.getMilliseconds() // millisecond
|
}
|
|
if (/(y+)/.test(format)) {
|
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
|
}
|
|
for (var k in o) {
|
if (new RegExp('(' + k + ')').test(format)) {
|
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
|
}
|
}
|
return format
|
}
|
|
// 消除字符串多余空格
|
if (!String.prototype.trim) {
|
// eslint-disable-next-line no-extend-native
|
String.prototype.trim = function() {
|
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
|
}
|
}
|
|
/**
|
* 获取本地缓存 localStorage
|
* @param {string} key storage 标记
|
* @return {*} 值
|
*/
|
function getLocalStorage(key) {
|
if (!key) {
|
return
|
}
|
var result = localStorage.getItem(key) || ''
|
try {
|
result = JSON.parse(result)
|
// eslint-disable-next-line no-empty
|
} catch (e) {}
|
return result
|
}
|
|
/**
|
* 获取本地缓存 sessionStorage
|
* @param {string} key storage 标记
|
* @return {*} 值
|
*/
|
function getSessionStorage(key) {
|
var result = sessionStorage.getItem(key) || ''
|
try {
|
result = JSON.parse(result)
|
// eslint-disable-next-line no-empty
|
} catch (e) {}
|
return result
|
}
|
|
/**
|
* 保存本地缓存 localStorage
|
* @param {string} key storage 标记
|
* @param {*} value 值
|
*/
|
function setLocalStorage(key, value) {
|
if (typeof value === 'object') {
|
value = JSON.stringify(value)
|
}
|
localStorage.setItem(key, value)
|
}
|
|
/**
|
* 保存本地缓存 sessionStorage
|
* @param {string} key storage 标记
|
* @param {*} value 值
|
*/
|
function setSessionStorage(key, value) {
|
if (typeof value === 'object') {
|
value = JSON.stringify(value)
|
}
|
sessionStorage.setItem(key, value)
|
}
|
|
/**
|
* 移除本地缓存 localStorage
|
* @param {string} key storage 标记
|
*/
|
function removeLocalStorage(key) {
|
localStorage.removeItem(key)
|
}
|
|
/**
|
* 移除本地缓存 sessionStorage
|
* @param {string} key storage 标记
|
*/
|
function removeSessionStorage(key) {
|
sessionStorage.removeItem(key)
|
}
|
|
/**
|
* 输入的价格限制在两位小数
|
* @param {string} number 价格
|
* @return {string} 过滤后的价格
|
*/
|
function toFixed2(number) {
|
number += ''
|
// eslint-disable-next-line eqeqeq
|
if (number == '') {
|
return ''
|
}
|
if (isNaN(number)) {
|
return ''
|
}
|
|
if (number.indexOf('.') > -1) {
|
var arr = number.split('.')
|
if (arr[1].length > 2) {
|
arr[1] = arr[1].substring(0, 2)
|
}
|
number = arr[0] + '.' + arr[1]
|
return number
|
}
|
|
return number
|
}
|
/**
|
* 价格转,分,为单位
|
* @param {string|number} price
|
*/
|
function amountFen(price) {
|
return parseInt(price * 100)
|
}
|
|
/**
|
* 获取查询字符串
|
* @param {string} name
|
* @param {string} url 默认 location.href
|
*/
|
function getQueryString(name, url) {
|
url = url || location.href
|
|
url = url.replace(/\#\S*/g, '')
|
|
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
|
var r = /\?/.test(url) && url.split('?')[1].match(reg)
|
if (r != null) {
|
return r[2]
|
}
|
return ''
|
}
|
|
// 全局缓存
|
var g_el = null
|
/**
|
* 绑定div滚动到底部
|
* @param {dom} el
|
* @param {function} callback
|
*/
|
function onReachBottom(el, callback) {
|
const offsetHeight = el.offsetHeight || window.outerHeight
|
const isWindow = el === window
|
g_el = el
|
|
el.onscroll = () => {
|
const scrollTop = isWindow ? document.documentElement.scrollTop : el.scrollTop
|
const scrollHeight = isWindow ? document.body.scrollHeight : el.scrollHeight
|
// console.log(scrollTop, scrollHeight)
|
// console.log(offsetHeight, scrollTop, scrollHeight)
|
if ((offsetHeight + scrollTop) - scrollHeight >= -1) {
|
typeof callback === 'function' && callback()
|
}
|
}
|
}
|
/**
|
* 取消绑定
|
* @param {dom} el
|
*/
|
function offReachBottom(el) {
|
el = el || g_el
|
el.onscroll = null
|
g_el = null
|
}
|
/**
|
* 生成唯一id
|
*/
|
function uuid() {
|
var s = []
|
var hexDigits = '0123456789abcdef'
|
for (var i = 0; i < 36; i++) {
|
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
|
}
|
s[14] = '4'
|
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
|
|
s[8] = s[13] = s[18] = s[23] = '-'
|
var uuid = s.join('')
|
return uuid
|
}
|
|
/**
|
* 替换当前链接,无返回
|
* @param {string} href
|
*/
|
function urlReplace(href) {
|
if (!href) {
|
return
|
}
|
if (href && /^#|javasc/.test(href) === false) {
|
if (history.replaceState) {
|
history.replaceState(null, document.title, href.split('#')[0] + '#')
|
location.replace(href)
|
} else {
|
location.replace(href)
|
}
|
}
|
}
|
|
/**
|
* 获取当前时间的对应的时间对象(如年月日,时分秒,星期几,时间戳)
|
* @param {Object} page 页面对象
|
* @param {String} key 时间对象的字段名
|
* @param {String} pageKey 页面关键词
|
*/
|
function countGetTime(page, key, pageKey) {
|
var dayStamp = new Date().getTime()
|
fn_obj[`timer_${pageKey}`] = null
|
var time = new Date(dayStamp)
|
var year = time.getFullYear()
|
let month = time.getMonth() + 1
|
let date = time.getDate()
|
let hours = time.getHours()
|
let minute = time.getMinutes()
|
let second = time.getSeconds()
|
|
if (month < 10) { month = '0' + month }
|
if (date < 10) { date = '0' + date }
|
if (hours < 10) { hours = '0' + hours }
|
if (minute < 10) { minute = '0' + minute }
|
if (second < 10) { second = '0' + second }
|
const weekNum = new Date().getDay()
|
const week = {
|
0: '星期天',
|
1: '星期一',
|
2: '星期二',
|
3: '星期三',
|
4: '星期四',
|
5: '星期五',
|
6: '星期六'
|
}
|
var res = {
|
week: week[weekNum ] ? week[weekNum ] : '日期错误',
|
day: `${year}年${month}月${date}日 ${hours}:${minute}:${second}`,
|
date: `${year}年${month}月${date}日`,
|
timeMin: `${hours}:${minute}`,
|
time: `${hours}:${minute}:${second}`,
|
timeStamp: dayStamp
|
}
|
page[key] = res
|
fn_obj[`timer_${pageKey}`] = setTimeout(() => {
|
countGetTime(page, key, pageKey)
|
}, 1000)
|
// console.log('1111111111111111111111', fn_obj)
|
}
|
|
/**
|
* 停止当前页面的计时功能
|
* @param {String} pageKey 页面关键词
|
*/
|
function stopCountGetTime(pageKey) {
|
clearTimeout(fn_obj[`timer_${pageKey}`])
|
fn_obj[`timer_${pageKey}`] = null
|
}
|
|
/**
|
* 轮询异步调用接口
|
* @param {Object} page 页面对象this
|
* @param {String} fnName 要轮询的方法名称
|
* @param {String} pageKey 页面关键字
|
* @param {Number} timeStamp 多少秒轮询
|
*/
|
function pollingAjaxFn(page, fnName, pageKey, timeStamp = 1000) {
|
if (!page || !fnName || !pageKey) {
|
return
|
}
|
page[fnName] && page[fnName]()
|
fn_obj[`pollingTimer_${pageKey}`] = setTimeout(() => {
|
pollingAjaxFn(page, fnName, pageKey, timeStamp)
|
}, timeStamp)
|
}
|
|
/**
|
* 停止轮询
|
* @param {String} pageKey 页面关键词
|
*/
|
function stopPollingAjaxFn(pageKey) {
|
clearTimeout(fn_obj[`pollingTimer_${pageKey}`])
|
fn_obj[`pollingTimer_${pageKey}`] = null
|
}
|
|
// 随机12位数
|
function getCheckedId() {
|
var s = []
|
var hexDigits = '0123456789abcdef'
|
for (var i = 0; i < 12; i++) {
|
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
|
}
|
// s[14] = '4';
|
// s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
|
|
// s[8] = s[13] = s[18] = s[23] = '-'
|
var uuid = s.join('')
|
return uuid
|
}
|
|
var fn = {
|
getLocalStorage,
|
getSessionStorage,
|
setLocalStorage,
|
setSessionStorage,
|
removeLocalStorage,
|
removeSessionStorage,
|
|
// eslint-disable-next-line indent
|
// eslint-disable-next-line indent
|
// 判断是否有滚动条,并获取滚动宽度
|
// getScrollBarWidth () {
|
// return hasScrollBar(document.body) ? getScrollBarWidth() : 0
|
// },
|
getScrollBarWidth,
|
|
toFixed2,
|
amountFen,
|
|
getQueryString,
|
onReachBottom,
|
offReachBottom,
|
|
uuid,
|
urlReplace,
|
|
countGetTime,
|
stopCountGetTime,
|
pollingAjaxFn,
|
stopPollingAjaxFn,
|
getCheckedId,
|
|
/**
|
* 深拷贝
|
* @param {object} obj 被复制的对象
|
* @return {object} 复制完成的对象
|
*/
|
deepCopyFN(obj) {
|
if (typeof obj !== 'object') {
|
return obj
|
}
|
|
let cloneObj = {}
|
switch (obj.constructor) {
|
case Array:
|
cloneObj = []
|
// eslint-disable-next-line no-fallthrough
|
case Object:
|
for (var property in obj) {
|
cloneObj[property] = typeof obj[property] === 'object' ? this.deepCopyFN(obj[property]) : obj[property]
|
}
|
break
|
case Map:
|
cloneObj = new Map()
|
obj.forEach((value, key) => {
|
cloneObj.set(key, typeof value === 'object' ? this.deepCopyFN(value) : value)
|
})
|
break
|
case Set:
|
cloneObj = new Set()
|
obj.forEach(value => {
|
cloneObj.add(typeof value === 'object' ? this.deepCopyFN(value) : value)
|
})
|
break
|
}
|
return cloneObj
|
}
|
}
|
export default fn
|