css 转成 html标签,html标签属性转成style

这个是为了转下xml上的color和size的属性的,被遗弃的font这个是支持的,但是size这个值跟现在的font-size不一致,再加上标准的也不再建议使用,所以才有下面的方法,当然也可以参考jquery或者zepto的方式来做,基本上是正则来处理的~

使用:attr2style('hellojs')

function attr2style(html){

const oBox = document.createElement('div')

oBox.innerHTML = html

if(oBox.childElementCount === 0) return html;

let hook = []

Array.prototype.slice.call(oBox.childNodes).map(function(el){

if(el.nodeType === 1){

let styles = {

color:el.getAttribute('color'),

size:el.getAttribute('size') ? el.getAttribute('size') + 'px' : 'initial'

}

el.style.cssText = `font-size:${styles.size};color:${styles.color};`

hook.push(el.outerHTML)

}else if(el.nodeType === 3){

hook.push(el.nodeValue)

}

})

return hook.join('')

}