大家好!我叫戴向天
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'))