jazz
2023-12-01 3ac5f24c0418692d7496fec49ce4d165fe24eb21
提交 | 用户 | age
3ac5f2 1 /*
J 2  * @Author: 丘骏_jun
3  * @Date: 2019-11-21 10:59:17
4  * @Last Modified by: 丘骏_jun
5  * @Last Modified time: 2019-12-30 16:29:45
6  */
7 // 通用function,通过全局安装,或import引用调用
8
9 let scrollBarWidth // 滚动条宽度
10 // 获取浏览器滚动条宽度
11 function getScrollBarWidth() {
12   if (scrollBarWidth !== undefined) return scrollBarWidth
13
14   const outer = document.createElement('div')
15   outer.className = 'el-scrollbar__wrap'
16   outer.style.visibility = 'hidden'
17   outer.style.width = '100px'
18   outer.style.position = 'absolute'
19   outer.style.top = '-9999px'
20   document.body.appendChild(outer)
21
22   const widthNoScroll = outer.offsetWidth
23   outer.style.overflow = 'scroll'
24
25   const inner = document.createElement('div')
26   inner.style.width = '100%'
27   outer.appendChild(inner)
28
29   const widthWithScroll = inner.offsetWidth
30   outer.parentNode.removeChild(outer)
31   scrollBarWidth = widthNoScroll - widthWithScroll
32
33   return scrollBarWidth
34 }
35 // 获取最近样式
36 // function getCurrentStyle (obj, prop) {
37 //     if (obj.currentStyle) {
38 //         return obj.currentStyle[prop];
39 //     } else if (window.getComputedStyle) {
40 //         prop = prop.replace(/([A-Z])/g, "-$1");
41 //         prop = prop.toLowerCase();
42 //         return document.defaultView.getComputedStyle(obj, null)[prop];
43 //     }
44 //     return null;
45 // }
46 // // 判断是否有滚动条
47 // function hasScrollBar (obj) {
48 //     return getCurrentStyle(obj, 'overflow') == 'hidden'
49 //         ? 0
50 //         : document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight);
51 // }
52
53 // 日期格式化
54 // eslint-disable-next-line no-extend-native
55 Date.prototype.format = function(format) {
56   var o = {
57     'M+': this.getMonth() + 1, // month
58     'd+': this.getDate(), // day
59     'H+': this.getHours(), // hour
60     'm+': this.getMinutes(), // minute
61     's+': this.getSeconds(), // second
62     'q+': Math.floor((this.getMonth() + 3) / 3), // quarter
63     'S': this.getMilliseconds() // millisecond
64   }
65
66   if (/(y+)/.test(format)) {
67     format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
68   }
69
70   for (var k in o) {
71     if (new RegExp('(' + k + ')').test(format)) {
72       format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
73     }
74   }
75   return format
76 }
77
78 // 消除字符串多余空格
79 if (!String.prototype.trim) {
80   // eslint-disable-next-line no-extend-native
81   String.prototype.trim = function() {
82     return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
83   }
84 }
85
86 /**
87  * 获取本地缓存 localStorage
88  * @param {string} key storage 标记
89  * @return {*} 值
90  */
91 function getLocalStorage(key) {
92   if (!key) {
93     return
94   }
95   var result = localStorage.getItem(key) || ''
96   try {
97     result = JSON.parse(result)
98   // eslint-disable-next-line no-empty
99   } catch (e) {}
100   return result
101 }
102
103 /**
104  * 获取本地缓存 sessionStorage
105  * @param {string} key storage 标记
106  * @return {*} 值
107  */
108 function getSessionStorage(key) {
109   var result = sessionStorage.getItem(key) || ''
110   try {
111     result = JSON.parse(result)
112   // eslint-disable-next-line no-empty
113   } catch (e) {}
114   return result
115 }
116
117 /**
118  * 保存本地缓存 localStorage
119  * @param {string} key storage 标记
120  * @param {*} value 值
121  */
122 function setLocalStorage(key, value) {
123   if (typeof value === 'object') {
124     value = JSON.stringify(value)
125   }
126   localStorage.setItem(key, value)
127 }
128
129 /**
130  * 保存本地缓存 sessionStorage
131  * @param {string} key storage 标记
132  * @param {*} value 值
133  */
134 function setSessionStorage(key, value) {
135   if (typeof value === 'object') {
136     value = JSON.stringify(value)
137   }
138   sessionStorage.setItem(key, value)
139 }
140
141 /**
142  * 移除本地缓存 localStorage
143  * @param {string} key storage 标记
144  */
145 function removeLocalStorage(key) {
146   localStorage.removeItem(key)
147 }
148
149 /**
150  * 移除本地缓存 sessionStorage
151  * @param {string} key storage 标记
152  */
153 function removeSessionStorage(key) {
154   sessionStorage.removeItem(key)
155 }
156
157 /**
158  * 输入的价格限制在两位小数
159  * @param {string} number 价格
160  * @return {string} 过滤后的价格
161  */
162 function toFixed2(number) {
163   number += ''
164   // eslint-disable-next-line eqeqeq
165   if (number == '') {
166     return ''
167   }
168   if (isNaN(number)) {
169     return ''
170   }
171
172   if (number.indexOf('.') > -1) {
173     var arr = number.split('.')
174     if (arr[1].length > 2) {
175       arr[1] = arr[1].substring(0, 2)
176     }
177     number = arr[0] + '.' + arr[1]
178     return number
179   }
180
181   return number
182 }
183 /**
184  * 价格转,分,为单位
185  * @param {string|number} price
186  */
187 function amountFen(price) {
188   return parseInt(price * 100)
189 }
190
191 /**
192  * 获取查询字符串
193  * @param {string} name
194  * @param {string} url 默认 location.href
195  */
196 function getQueryString(name, url) {
197   url = url || location.href
198
199   url = url.replace(/\#\S*/g, '')
200
201   var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
202   var r = /\?/.test(url) && url.split('?')[1].match(reg)
203   if (r != null) {
204     return r[2]
205   }
206   return ''
207 }
208
209 // 全局缓存
210 var g_el = null
211 /**
212  * 绑定div滚动到底部
213  * @param {dom} el
214  * @param {function} callback
215  */
216 function onReachBottom(el, callback) {
217   const offsetHeight = el.offsetHeight || window.outerHeight
218   const isWindow = el === window
219   g_el = el
220
221   el.onscroll = () => {
222     const scrollTop = isWindow ? document.documentElement.scrollTop : el.scrollTop
223     const scrollHeight = isWindow ? document.body.scrollHeight : el.scrollHeight
224     // console.log(scrollTop, scrollHeight)
225     // console.log(offsetHeight, scrollTop, scrollHeight)
226     if ((offsetHeight + scrollTop) - scrollHeight >= -1) {
227       typeof callback === 'function' && callback()
228     }
229   }
230 }
231 /**
232  * 取消绑定
233  * @param {dom} el
234  */
235 function offReachBottom(el) {
236   el = el || g_el
237   el.onscroll = null
238   g_el = null
239 }
240 /**
241  * 生成唯一id
242  */
243 function uuid() {
244   var s = []
245   var hexDigits = '0123456789abcdef'
246   for (var i = 0; i < 36; i++) {
247     s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
248   }
249   s[14] = '4'
250   s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
251
252   s[8] = s[13] = s[18] = s[23] = '-'
253   var uuid = s.join('')
254   return uuid
255 }
256
257 /**
258  * 替换当前链接,无返回
259  * @param {string} href
260  */
261 function urlReplace(href) {
262   if (!href) {
263     return
264   }
265   if (href && /^#|javasc/.test(href) === false) {
266     if (history.replaceState) {
267       history.replaceState(null, document.title, href.split('#')[0] + '#')
268       location.replace(href)
269     } else {
270       location.replace(href)
271     }
272   }
273 }
274
275 /**
276  * 获取当前时间的对应的时间对象(如年月日,时分秒,星期几,时间戳)
277  * @param {Object} page 页面对象
278  * @param {String} key 时间对象的字段名
279  */
280 function countGetTime(page, key) {
281   var dayStamp = new Date().getTime()
282   var timer = null
283   var time = new Date(dayStamp)
284   var year = time.getFullYear()
285   let month = time.getMonth() + 1
286   let date = time.getDate()
287   let hours = time.getHours()
288   let minute = time.getMinutes()
289   let second = time.getSeconds()
290
291   if (month < 10) { month = '0' + month }
292   if (date < 10) { date = '0' + date }
293   if (hours < 10) { hours = '0' + hours }
294   if (minute < 10) { minute = '0' + minute }
295   if (second < 10) { second = '0' + second }
296   const weekNum = new Date().getDay()
297   const week = {
298     0: '星期天',
299     1: '星期一',
300     2: '星期二',
301     3: '星期三',
302     4: '星期四',
303     5: '星期五',
304     6: '星期六'
305   }
306   var res = {
307     week: week[weekNum ] ? week[weekNum ] : '日期错误',
308     day: `${year}年${month}月${date}日 ${hours}:${minute}:${second}`,
309     date: `${year}年${month}月${date}日`,
310     timeMin: `${hours}:${minute}`,
311     time: `${hours}:${minute}:${second}`,
312     timeStamp: dayStamp
313   }
314   // console.log('1111111111111111111111', page, key)
315   page[key] = res
316   timer = setTimeout(() => {
317     countGetTime(page, key)
318     clearTimeout(timer)
319     timer = null
320   }, 1000)
321 }
322
323 var fn = {
324   getLocalStorage,
325   getSessionStorage,
326   setLocalStorage,
327   setSessionStorage,
328   removeLocalStorage,
329   removeSessionStorage,
330
331   // eslint-disable-next-line indent
332     // eslint-disable-next-line indent
333     // 判断是否有滚动条,并获取滚动宽度
334   // getScrollBarWidth () {
335   //     return hasScrollBar(document.body) ? getScrollBarWidth() : 0
336   // },
337   getScrollBarWidth,
338
339   toFixed2,
340   amountFen,
341
342   getQueryString,
343   onReachBottom,
344   offReachBottom,
345
346   uuid,
347   urlReplace,
348
349   countGetTime,
350
351   /**
352      * 深拷贝
353      * @param {object} obj 被复制的对象
354      * @return {object} 复制完成的对象
355      */
356   deepCopyFN(obj) {
357     if (typeof obj !== 'object') {
358       return obj
359     }
360
361     let cloneObj = {}
362     switch (obj.constructor) {
363       case Array:
364         cloneObj = []
365       // eslint-disable-next-line no-fallthrough
366       case Object:
367         for (var property in obj) {
368           cloneObj[property] = typeof obj[property] === 'object' ? this.deepCopyFN(obj[property]) : obj[property]
369         }
370         break
371       case Map:
372         cloneObj = new Map()
373         obj.forEach((value, key) => {
374           cloneObj.set(key, typeof value === 'object' ? this.deepCopyFN(value) : value)
375         })
376         break
377       case Set:
378         cloneObj = new Set()
379         obj.forEach(value => {
380           cloneObj.add(typeof value === 'object' ? this.deepCopyFN(value) : value)
381         })
382         break
383     }
384     return cloneObj
385   }
386 }
387 export default fn