all files / dom/class/ compact.js

97.44% Statements 38/39
85.19% Branches 23/27
100% Functions 13/13
97.44% Lines 38/39
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77          12× 12× 12× 12× 12×                                     193×   193×       188×   188× 161× 186×     188×                  
import { avalon, rnowhite, rword } from '../../seed/core'
 
export function ClassList(node) {
    this.node = node
}
 
ClassList.prototype = {
    toString() {
        var node = this.node
        var cls = node.className
        var str = typeof cls === 'string' ? cls : cls.baseVal
        var match = str.match(rnowhite)
        return match ? match.join(' ') : ''
    },
    contains(cls) {
        return (' ' + this + ' ').indexOf(' ' + cls + ' ') > -1
    },
    add(cls) {
        Eif (!this.contains(cls)) {
            this.set(this + ' ' + cls)
        }
    },
    remove(cls) {
        this.set((' ' + this + ' ').replace(' ' + cls + ' ', ' '))
    },
    set(cls) {
        cls = cls.trim()
        var node = this.node
        if (typeof node.className === 'object') {
            //SVG元素的className是一个对象 SVGAnimatedString { baseVal='', animVal=''},只能通过set/getAttribute操作
            node.setAttribute('class', cls)
        } else {
            node.className = cls
        }
        Iif (!cls) {
            node.removeAttribute('class')
        }
        //toggle存在版本差异,因此不使用它
    }
}
 
export function classListFactory(node) {
    if (!('classList' in node)) {
        node.classList = new ClassList(node)
    }
    return node.classList
}
 
 
'add,remove'.replace(rword, function(method) {
    avalon.fn[method + 'Class'] = function(cls) {
        var el = this[0] || {}
            //https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
        if (cls && typeof cls === 'string' && el.nodeType === 1) {
            cls.replace(rnowhite, function(c) {
                classListFactory(el)[method](c)
            })
        }
        return this
    }
})
 
avalon.shadowCopy(avalon.fn, {
    hasClass: function(cls) {
        var el = this[0] || {}
        return el.nodeType === 1 && classListFactory(el).contains(cls)
    },
    toggleClass: function(value, stateVal) {
        var isBool = typeof stateVal === 'boolean'
        var me = this
        String(value).replace(rnowhite, function(c) {
            var state = isBool ? stateVal : !me.hasClass(c)
            me[state ? 'addClass' : 'removeClass'](c)
        })
        return this
    }
})