index.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // @ts-nocheck
  2. // #ifndef UNI-APP-X && APP
  3. interface CSSProperties {
  4. [key : string] : string | number | null
  5. }
  6. // #endif
  7. // #ifdef VUE3
  8. // #ifdef UNI-APP-X && APP
  9. type CSSProperties = UTSJSONObject
  10. // #endif
  11. // #endif
  12. /**
  13. * 将字符串转换为带有连字符分隔的小写形式
  14. * @param key - 要转换的字符串
  15. * @returns 转换后的字符串
  16. */
  17. export function toLowercaseSeparator(key : string):string {
  18. return key.replace(/([A-Z])/g, '-$1').toLowerCase();
  19. }
  20. /**
  21. * 获取样式对象对应的样式字符串
  22. * @param style - CSS样式对象
  23. * @returns 由非空有效样式属性键值对组成的字符串
  24. */
  25. export function getStyleStr(style : CSSProperties) : string {
  26. // #ifdef UNI-APP-X && APP
  27. let styleStr = '';
  28. style.toMap().forEach((value, key) => {
  29. if(value !== null && value != '') {
  30. styleStr += `${toLowercaseSeparator(key as string)}: ${value};`
  31. }
  32. })
  33. return styleStr
  34. // #endif
  35. // #ifndef UNI-APP-X && APP
  36. return Object.keys(style)
  37. .filter(
  38. (key) =>
  39. style[key] !== undefined &&
  40. style[key] !== null &&
  41. style[key] !== '')
  42. .map((key : string) => `${toLowercaseSeparator(key)}: ${style[key]};`)
  43. .join(' ');
  44. // #endif
  45. }
  46. // 示例
  47. // const style = { color: 'red', fontSize: '16px', backgroundColor: '', border: null };
  48. // const styleStr = getStyleStr(style);
  49. // console.log(styleStr);
  50. // 输出: "color: red; font-size: 16px;"