使用样式定义解析类属性

时间:2012-04-13 16:16:45

标签: c# html css regex styles

我将具体说明:

如何替换

<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#)呢?正则表达式?有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

使用此工具将HTML / CSS转换为内联CSS。=

http://inlinestyler.torchboxapps.com

如果您必须使用此功能,例如使用基于HTML的电子邮件等样式。

相关问题