这里记录一下使用到常用的js文件以及一些常用到的工具类函数。(陆续更新...)
<script>
/**
* 1rem = 100px,基于 1920px 的宽度比例
* 单位统一保留三位小数(转换成 px 为一位小数),e.g.: width: 0.125rem;(12.5px)
*/
function setRem() {
const size = 19.2;
const html = document.documentElement;
window.rem = html.getBoundingClientRect().width / size;
html.style.fontSize = window.rem + "px";
}
window.addEventListener("resize", setRem, false);
setRem();
</script>
// 动态计算相应的比例值
function jsNum(num) {
let lenWindow = document.documentElement.clientWidth;
let iWidth = lenWindow / 1920;
let fs = num * iWidth;
return fs;
// 组件通信
export class EvtMsg {
evts
constructor () {
this.evts = {}
}
on (event: string, cb) {
if(!event || typeof cb !== 'function') return
if(!this.evts[event]) {
this.evts[event] = []
}
this.evts[event].push(cb)
}
emit (event, ...arg) {
if (!event || !this.evts[event]) return
const cbs = this.evts[event]
for(let i=0; i<cbs.length; i++) {
const cb = cbs[i]
cb.apply(this, arg)
}
}
off (event: string, cb) {
if (!event || !this.evts[event]) return
const cbs = this.evts[event]
const idx = cbs.findIndex(c => c === cb)
cbs.splice(idx, 1)
return
}
removeAll () {
this.evts = {}
}
}
export const eventBus = new EvtMsg()
}
/** 防抖 */
export const debounce = (fn, delay = 500) => {
let timerId
return (...rest) => {
const args = rest
if (timerId) clearTimeout(timerId)
timerId = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
/** 字符串转json */
export function strToJson (str) {
let result = str
try {
result = new Function('return ' + str)()
} catch(err) {
} finally {
return result
}
}
/** 节流*/
export function throttle (func: Function, wait?: number, options: any = {}) {
let timer: any = null
return function (...args) {
const context = options.context || this
if (timer) {
return
}
timer = setTimeout(function () {
func.apply(context, args)
clearTimeout(timer)
timer = null
}, wait || 1000)
}
}
网友评论