jazz
2023-12-01 3ac5f24c0418692d7496fec49ce4d165fe24eb21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
 * @Author: 丘骏_jun
 * @Date: 2019-11-21 10:59:17
 * @Last Modified by: 丘骏_jun
 * @Last Modified time: 2019-12-30 16:29:45
 */
// 通用function,通过全局安装,或import引用调用
 
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 时间对象的字段名
 */
function countGetTime(page, key) {
  var dayStamp = new Date().getTime()
  var timer = 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
  }
  // console.log('1111111111111111111111', page, key)
  page[key] = res
  timer = setTimeout(() => {
    countGetTime(page, key)
    clearTimeout(timer)
    timer = null
  }, 1000)
}
 
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,
 
  /**
     * 深拷贝
     * @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