index.ts 956 B

123456789101112131415161718192021222324252627282930
  1. // @ts-nocheck
  2. interface CSSProperties {
  3. [key: string]: string | number
  4. }
  5. /**
  6. * 将字符串转换为带有连字符分隔的小写形式
  7. * @param key - 要转换的字符串
  8. * @returns 转换后的字符串
  9. */
  10. export function toLowercaseSeparator(key: string) {
  11. return key.replace(/([A-Z])/g, '-$1').toLowerCase();
  12. }
  13. /**
  14. * 获取样式对象对应的样式字符串
  15. * @param style - CSS样式对象
  16. * @returns 由非空有效样式属性键值对组成的字符串
  17. */
  18. export function getStyleStr(style: CSSProperties): string {
  19. return Object.keys(style)
  20. .filter(key => style[key] !== undefined && style[key] !== null && style[key] !== '')
  21. .map((key: string) => `${toLowercaseSeparator(key)}: ${style[key]};`)
  22. .join(' ');
  23. }
  24. // 示例
  25. // const style = { color: 'red', fontSize: '16px', backgroundColor: '', border: null };
  26. // const styleStr = getStyleStr(style);
  27. // console.log(styleStr);
  28. // 输出: "color: red; font-size: 16px;"