web
9 小时以前 49fa0d82a40345342966e810b44429aec0480ef3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// @ts-nocheck
// #ifndef UNI-APP-X && APP
interface CSSProperties {
    [key : string] : string | number | null
}
// #endif
 
// #ifdef VUE3
// #ifdef UNI-APP-X && APP
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 {
    
    // #ifdef UNI-APP-X && APP
    let styleStr = '';
    style.toMap().forEach((value, key) => {
        if(value !== null && value != '') {
            styleStr += `${toLowercaseSeparator(key as string)}: ${value};`
        }
    })
    return styleStr
    // #endif
    // #ifndef UNI-APP-X && APP
    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;"