/** css属性 字符串 转 驼峰写法 */ export function camelize(str: string) { return str.replace(/-+(.)?/g, function (match, chr) { return chr ? chr.toUpperCase() : '' }); } /** css属性 驼峰写法 转 字符串 */ export function dasherize(str: string) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } /** 根据节点id 获取样式规则 */ export function getStyleSheetByNodeId(id: string, doc: Document) { for (let i = 0; i < doc.styleSheets.length; i++) { let sheet = doc.styleSheets.item(i) as CSSStyleSheet; if ((sheet.ownerNode as HTMLElement).id === id) { return sheet; } } return null; } /** 遍历规则 */ export function forEachCssStyleRules(styleSheet: CSSStyleSheet, fn: (rule: CSSStyleRule, index: number) => void) { if (fn) { for (let i = 0; i < styleSheet.cssRules.length; i++) { fn(styleSheet.cssRules.item(i) as CSSStyleRule, i); } } } /** 根据样式名获取 样式规则对象 */ export function getCssStyleRule(selector: string, styleSheet: CSSStyleSheet) { for (let i = 0; i < styleSheet.cssRules.length; i++) { let rule = styleSheet.cssRules.item(i) as CSSStyleRule; if (rule.selectorText === selector) { return rule; } } return null; } /** 删除样式规则 */ export function deleteCssStyleRule(selector: string, styleSheet: CSSStyleSheet) { forEachCssStyleRules(styleSheet, (rule, index) => { rule.selectorText === selector && styleSheet.deleteRule(index); }); } /** 创建样式节点并返回该 节点及样式对象 */ export function createStyleSheet(doc: Document): [HTMLElement, CSSStyleSheet] | null { try { let style = doc.createElement('style'); doc.head.appendChild(style); for (let sheet of doc.styleSheets as any) { if (sheet.ownerNode === style) { return [style, sheet]; } } } catch { console.log('浏览器版本不支持 StyleSheet 的迭代器') } return null; }