2011-09-26 41 views
2

我正在尝试设置一种将基于干净样式表的设计转换为丑陋内联样式设计(用于时事通讯编辑器)的自动方法。使用jQuery制作样式内联样式

是否有可能得到所有的风格,适用于某个元素(DIV,P,跨度,H1,H2等),并将其应用到该元素为内联?

因此而不是我的风格漂亮和美丽这样一个样式表:

#topHeader { color: #222; background: red; width: 210px; height: 110px;} 

有它内联这样的:

<div id="topHeader" style="color: #222; background: red; width: 210px; height: 110px;"> 

如果有谁知道,如果这是在所有可能,如果可以的话请给我正确的方向。

不管怎样,谢谢:)

回答

0

你可能做到这一点使用的.style成员您正在引用的DOM元素。使用你的榜样,或许真的沿着这些线路(未经测试):

var el  = document.getElementById('topHeader'); 
var styles = new Array(); 

for (var key in el.style) { 
    // You'll probably need to do some more conditional work here... 
    if (el.style[key]) { 
     styles.push(key + ': ' + el.style[key]); 
    } 
} 

el.setAttribute('style', styles.join('; ')); 
+0

有趣的..今天晚些时候会试用它。感谢你及时的答复! – askenielsen

0

你可以遍历文档的样式表和规则:

$.each(document.styleSheets, function() { 
    $.each(this.cssRules || this.rules, function() { 
     var style = {}; 
     var styles = this.cssText.split(/;\s*/g); 
     $.each(styles, function() { 
      var parts = styles.split(/\:\s*/g); 
      style[parts[0]] = parts[1]; 
     }); 
     $(this.selectorText).css(style); 
    }); 
}); 

并非所有浏览器揭露.selectorText,并.cssText都需要特定的浏览器的解析。希望这足以让你指向正确的方向。

0

我用一定的成功如下:

$('#parentidhere').find('*').each(function (i, elem){elem.style.cssText=document.defaultView.getComputedStyle(elem,"").cssText;}); 

喜欢的背景选择了更为复杂的造型某些造型似乎仍然虽然消失了,我一直没能找出原因呢。 这也不适用于旧版浏览器,但在我的情况下,这并不重要。