cxc-szcx-uniapp/uni_modules/lime-shared/getStyleStr/index.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-09-14 02:26:50 +00:00
// @ts-nocheck
2025-02-11 01:34:29 +00:00
// #ifndef UNI-APP-X && APP
2024-09-14 02:26:50 +00:00
interface CSSProperties {
[key : string] : string | number | null
}
// #endif
// #ifdef VUE3
2025-02-11 01:34:29 +00:00
// #ifdef UNI-APP-X && APP
2024-09-14 02:26:50 +00:00
type CSSProperties = UTSJSONObject
// #endif
// #endif
/**
*
* @param key -
* @returns
*/
export function toLowercaseSeparator(key : string):string {
return key.replace(/([A-Z])/g, '-$1').toLowerCase();
}
/**
*
* @param style - CSS样式对象
* @returns
*/
export function getStyleStr(style : CSSProperties) : string {
2025-02-11 01:34:29 +00:00
// #ifdef UNI-APP-X && APP
2024-09-14 02:26:50 +00:00
let styleStr = '';
style.toMap().forEach((value, key) => {
if(value !== null && value != '') {
styleStr += `${toLowercaseSeparator(key as string)}: ${value};`
}
})
return styleStr
// #endif
2025-02-11 01:34:29 +00:00
// #ifndef UNI-APP-X && APP
2024-09-14 02:26:50 +00:00
return Object.keys(style)
.filter(
(key) =>
style[key] !== undefined &&
style[key] !== null &&
style[key] !== '')
.map((key : string) => `${toLowercaseSeparator(key)}: ${style[key]};`)
.join(' ');
// #endif
}
// 示例
// const style = { color: 'red', fontSize: '16px', backgroundColor: '', border: null };
// const styleStr = getStyleStr(style);
// console.log(styleStr);
// 输出: "color: red; font-size: 16px;"