index.ts 1.2 KB

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