computeClass, computeStyle(计算类名/样式合集)
- 简述:类似于 Vue 的 class, style 属性序列计算方法,将类名/样式整合到一个合集里。
- 兼容性:运行环境需支持
Array.prototype.flat,兼容方案可参考此处。
源码
function computeClass(value, toStr) {
const res = []
for (let item of [value].flat(Infinity)) {
if (!item) continue
if (typeof item == 'string') {
for (let val of item.split(' ')) (val = val.trim()) && !res.includes(val) && res.push(val)
} else if (typeof item == 'object') {
for (let key in item) key && item[key] && !res.includes(key) && res.push(key)
}
}
return toStr ? res.join(' ') : res
}
function computeStyle(value, toStr) {
const res = {}, noHump = (v) => v.replace(/(^[A-Z])|[A-Z]/g, ($0, $1) => `${$1 ? '' : '-'}${$0.toLowerCase()}`)
for (let item of [value].flat(Infinity)) {
if (!item) continue
if (typeof item == 'string') {
for (let val of item.split(';')) {
val = val.split(':')
if (val.length == 2 && (val[0] = val[0].trim())) {
res[val[0].startsWith('--') ? val[0] : noHump(val[0])] = val[1].trim()
}
}
} else if (typeof item == 'object') {
for (let key in item) {
let val = item[key], str = typeof val == 'string' || typeof val == 'number'
res[key.startsWith('--') ? key : noHump(key)] = str ? String(val) : Array.isArray(val) ? val.join(', ') : ''
}
}
}
if (toStr) {
let str = ''
for (let key in res) str += `${key}: ${res[key]}; `
return str.trim()
}
return res
}
使用示例
var rawClass = [
'c1', 'c2 c3', { c3: true, c4: true, c5: false },
['c6', ['c6', 'c7'], { c8: 0, c9: 1 }]
]
computeClass(rawClass)
computeClass(rawClass, true)
var rawStyle = [
'--a-var1-AA: 10%;', 'width: 10px',
'height: 20px; line-height: 30px; font-size: ;',
{ '--a-var1-AA': '11%', '--a-var2-BB': '20%', lineHeight: '40px', 'border-width': ['2px'] },
['color: red', ['background: blue', {
background: '', backgroundColor: 'green', boxShadow: ['0 0 1px blue', 'inset 0 0 1px red']
}]]
]
computeStyle(rawStyle)
computeStyle(rawStyle, true)