2012-04-13 128 views
0

我会很具体:解析类属性

如何更换

<style type="text/css"> 
    .class1 {font-weight:bold; font-size:10pt;} 
    .class2 {font-weight:bold; font-size:12pt;} 
    ... 
    .classN {font-weight:bold; font-size:8pt; vertical-align:sub;} 
</style> 

<div class="class2" style="color:blue;"> 
    Bold Text 
</div> 

有了这个:

<div style="color:blue; font-weight:bold; font-size:12pt;"> 
    Bold Text 
</div> 

**注意 - 节点可以是任何节点 - 属性顺序不关心。 - 类属性不需要被剥离

有什么HTML方法(C#)来做到这一点?正则表达式?有任何想法吗?

在此先感谢!

+0

您想从样式块中移除样式规则并将它们内联移动?你想在运行时做到这一点? – steveax 2012-04-13 16:20:20

+0

正确,内联和在运行时。 – stevenpacho 2012-04-13 16:24:11

+0

我认为你首先打败了风格的整个目的。为什么不让浏览器为你处理这个问题 – Ibu 2012-04-13 16:25:07

回答

0

如果您正在使用jQuery,你可以使用这个插件:

/* 
* getStyleObject Plugin for jQuery JavaScript Library 
* From: http://upshots.org/?p=112 
* 
* Copyright: Unknown, see source link 
* Plugin version by Dakota Schneider (http://hackthetruth.org) 
*/ 

(function($){ 
    $.fn.getStyleObject = function(){ 
     var dom = this.get(0); 
     var style; 
     var returns = {}; 
     if(window.getComputedStyle){ 
      var camelize = function(a,b){ 
       return b.toUpperCase(); 
      } 
      style = window.getComputedStyle(dom, null); 
      for(var i=0;i<style.length;i++){ 
       var prop = style[i]; 
       var camel = prop.replace(/\-([a-z])/g, camelize); 
       var val = style.getPropertyValue(prop); 
       returns[camel] = val; 
      } 
      return returns; 
     } 
     if(dom.currentStyle){ 
      style = dom.currentStyle; 
      for(var prop in style){ 
       returns[prop] = style[prop]; 
      } 
      return returns; 
     } 
     return this.css(); 
    } 
})(jQuery); 

和尝试这样的事情

<div class="class2" style="color:blue;"> 
    Bold Text 
</div> 
<script type="text/javascript"> 
    var computedStyle; 
    $("div[class^='class']").each(function(){ 
    computedStyle = $(this).getStyleObject(); 
    $(this).css(computedStyle); 
    $(this).attr('class',''); 
    }); 
</script> 
+0

好的,我发现了一个类似的问题,可以解决我的问题问题在C# 谢谢大家! [] [1] [1]:http://stackoverflow.com/questions/3679213/inlining-css-in-c-sharp – stevenpacho 2012-04-13 17:01:38