@mdui/jq
Version:
拥有和 jQuery 相似 API 的轻量级 JavaScript 工具库
121 lines (120 loc) • 3.25 kB
JavaScript
/**
* 获取指定元素的标签名(小写),不存在元素的返回空字符串
* @param element
*/
export const getNodeName = (element) => {
return element?.nodeName.toLowerCase() ?? '';
};
/**
* 判断元素是否为指定的标签名(不区分大小写)
* @param element
* @param name
*/
export const isNodeName = (element, name) => {
return element?.nodeName.toLowerCase() === name.toLowerCase();
};
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
export const isFunction = (target) => {
return typeof target === 'function';
};
export const isString = (target) => {
return typeof target === 'string';
};
export const isNumber = (target) => {
return typeof target === 'number';
};
export const isBoolean = (target) => {
return typeof target === 'boolean';
};
export const isUndefined = (target) => {
return typeof target === 'undefined';
};
export const isNull = (target) => {
return target === null;
};
export const isWindow = (target) => {
return typeof Window !== 'undefined' && target instanceof Window;
};
export const isDocument = (target) => {
return typeof Document !== 'undefined' && target instanceof Document;
};
export const isElement = (target) => {
return typeof Element !== 'undefined' && target instanceof Element;
};
export const isNode = (target) => {
return typeof Node !== 'undefined' && target instanceof Node;
};
export const isArrayLike = (target) => {
return (!isFunction(target) &&
!isWindow(target) &&
isNumber(target.length));
};
export const isObjectLike = (target) => {
return typeof target === 'object' && target !== null;
};
export const toElement = (target) => {
return isDocument(target) ? target.documentElement : target;
};
/**
* 把用 - 分隔的字符串转为驼峰(如 box-sizing 转换为 boxSizing)
* @param string
*/
export const toCamelCase = (string) => {
return string.replace(/-([a-z])/g, (_, letter) => {
return letter.toUpperCase();
});
};
/**
* 把驼峰法转为用 - 分隔的字符串(如 boxSizing 转换为 box-sizing)
* @param string
*/
export const toKebabCase = (string) => {
if (!string) {
return string;
}
return string
.replace(/^./, string[0].toLowerCase()) // 首字母转小写
.replace(/[A-Z]/g, (replacer) => {
return '-' + replacer.toLowerCase();
});
};
/**
* 始终返回 false 的函数
*/
export const returnFalse = () => {
return false;
};
/**
* 始终返回 true 的函数
*/
export const returnTrue = () => {
return true;
};
/**
* 遍历数组
* @param target
* @param callback
*/
export const eachArray = (target, callback) => {
for (let i = 0; i < target.length; i += 1) {
if (callback.call(target[i], target[i], i) === false) {
return target;
}
}
return target;
};
/**
* 遍历对象
* @param target
* @param callback
*/
export const eachObject = (target, callback) => {
const keys = Object.keys(target);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (callback.call(target[key], key, target[key]) === false) {
return target;
}
}
return target;
};