# all files / src/ style.js

96.3% Statements 26/27
86.36% Branches 19/22
100% Functions 2/2
96.3% Lines 26/27

    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
    55
    56
    57
    58
    59
    60
    61
    62
    63
    1×

    5×
    1×

    4×
    4×
    3×
    3×
    3×
    3×
    2×
    1×

    3×

    4×
    5×
    2×

    1×

    1×
    1×

    4×
    2×

    2×
    2×
    6×
    6×
    1×

    1×
     import { oneObject, camelize } from './util'
    export var rnumber = /^-?\d+(\.\d+)?$/
        /**
         * 为元素样子设置样式
         *
         * @export
         * @param {any} dom
         * @param {any} oldStyle
         * @param {any} newStyle
         */
    export function patchStyle(dom, oldStyle, newStyle) {
        if (oldStyle === newStyle) {
            return
        }
        var old = {}
        for (var name in newStyle) {
            let val = newStyle[name]
            Eif (oldStyle[name] !== val) {
                name = cssName(name, dom)
                if (val === void(0) || val === null || val === false) {
                    val = '' //清除样式
                } else Iif (rnumber.test(val) && !cssNumber[name]) {
                    val = val + 'px' //添加单位
                }
                dom.style[name] = val //应用样式
            }
        }
        // 如果旧样式存在，但新样式已经去掉
        for (var name in oldStyle) {
            if (!(name in newStyle)) {
                dom.style[name] = '' //清除样式
            }
        }
    }

    export var cssNumber = oneObject('animationIterationCount,columnCount,order,flex,flexGrow,flexShrink,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom')

    //var testStyle = document.documentElement.style
    var prefixes = ['', '-webkit-', '-o-', '-moz-', '-ms-']
    export var cssMap = oneObject('float', 'cssFloat')

    /**
     * 转换成当前浏览器可用的样式名
     *
     * @param {any} name
     * @returns
     */
    export function cssName(name, dom) {
        if (cssMap[name]) {
            return cssMap[name]
        }
       var host = dom && dom.style || {}
        for (var i = 0, n = prefixes.length; i < n; i++) {
            var camelCase = camelize(prefixes[i] + name)
            if (camelCase in host) {
                return (cssMap[name] = camelCase)
            }
        }
        return null
    }