JS bridge
JS Bridge 通信原理
https://mp.weixin.qq.com/s/T78J3dM9i5TvLu0h6joX3A
操作class
// 查询class
export const hasClass = function(obj, cls) {
return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
// 添加class
export const addClass = function(obj, cls) {
if (!hasClass(obj, cls)) obj.className += ' ' + cls;
};
// 移除class
export const removeClass = function(obj, cls) {
if (hasClass(obj, cls)) {
const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
obj.className = obj.className.replace(reg, ' ');
}
};
// class切换
export const toggleClass = function(obj, cls) {
if (hasClass(obj, cls)) {
removeClass(obj, cls);
} else {
addClass(obj, cls);
}
};
js 判断
// 判断是null or undefined or ''
export const isEmpty = function (val) {
// null or undefined
if (val == null) return true
if (typeof val === 'boolean') return false
if (typeof val === 'number') return !val
if (val instanceof Error) return val.message === ''
switch (Object.prototype.toString.call(val)) {
// String or Array
case '[object String]':
case '[object Array]':
return !val.length
// Map or Set or File
case '[object File]':
case '[object Map]':
case '[object Set]': {
return !val.size
}
// Plain Object
case '[object Object]': {
return !Object.keys(val).length
}
}
return false
}
export function isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]'
}
export function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
export function isArray(value) {
return value instanceof Array
}
export function isHtmlElement(node) {
return node && node.nodeType === Node.ELEMENT_NODE
}
export const isFunction = (functionToCheck) => {
var getType = {}
return (
functionToCheck &&
getType.toString.call(functionToCheck) === '[object Function]'
)
}
export const isUndefined = (val) => {
// eslint-disable-next-line no-void
return val === void 0
}
export const isDefined = (val) => {
return val !== undefined && val !== null
}
// 是否相等
// 数组、字符串、数字(对象不行)
export const valueEquals = (a, b) => {
// see: https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
if (a === b) return true
if (!(a instanceof Array)) return false
if (!(b instanceof Array)) return false
if (a.length !== b.length) return false
for (let i = 0; i !== a.length; ++i) {
if (a[i] !== b[i]) return false
}
return true
}