JS将样式表的样式转换成行内样式 sheetToSelf - 戴向天

大家好!我叫戴向天

QQ群:602504799

如若有不理解的,可加QQ群进行咨询了解

// 将样式表的样式装换成行内样式
let sheetToSelf = function(dom){
      const sheets = document.styleSheets;
      const sheetsArry = Array.from(sheets);
      const $dom = dom.parentNode
	  
		function cssTextToJSON(cssText){
			const arr = cssText.split(';')
			arr.splice(arr.length- 1 ,1)
			const obj = {}
			arr.forEach(function(item){
				const attrName = item.split(':')[0]
				obj[attrName.replace(/ /g,'')] = item.split(':').map(function(i,index){
					return index?i:''
				}).join('')
			})
			return obj
		}
	  
      sheetsArry.forEach(function(sheetContent){
        const { rules, cssRules } = sheetContent;
        //cssRules兼容火狐
        const rulesArry = Array.from(rules || cssRules || []);
        rulesArry.forEach( rule => {
          const { selectorText, style } = rule;
          if (selectorText !== '*') {
            try {
              const select = $dom.querySelectorAll(selectorText);
              select.forEach( function(dom) {
				if(dom.style.cssText){
					const oldCssText = cssTextToJSON(dom.style.cssText);
					const newCssText = cssTextToJSON(style.cssText);
					for(let i in newCssText){
						oldCssText[i] = newCssText[i]
					}
					for(let i in oldCssText){
						dom.style[i] = oldCssText[i]
					}
				}else{
					dom.style.cssText = style.cssText
				}
			 })
            } catch (e) {
              console.log('转换成行内样式失败',e);
            }
          }
        })
      })
    }
sheetToSelf(document.querySelector('#app'))

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/106767106