2012-04-13 123 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