使用jquery将CSS复制到内联(或在从网页复制内容时保留格式)

时间:2021-06-05 23:54:36

I could probably muddle through the code for this, but before I do I thought I'd ask if there's a quick and/or built-in way or plugin for this...

我可能会混淆代码,但在此之前,我想我会问这是否有快速和/或内置方式或插件...

Given a table with a css class applied to it, the class definition being in an external style sheet (with styles applied to th, tr, and td) I want to move OR copy that css to the style attribute of the tags themselves. In other words I want to make the CSS inline.

给定一个应用了css类的表,类定义在外部样式表中(样式应用于th,tr和td)我想移动或将该css复制到标记本身的style属性。换句话说,我想让CSS内联。

Reason: People who use these pages sometimes copy and paste the tables into emails. If they do this on a table with externally-sourced CSS the pasted table has lost all formatting. If the css is inline the formatting is retained.

原因:使用这些页面的人有时会将表格复制并粘贴到电子邮件中。如果他们在具有外部源CSS的表上执行此操作,则粘贴的表将丢失所有格式。如果css是内联的,则保留格式。

I have already done this in a rough-and-ready way by simply applying duplicated css to the table using $().css(); function, but this is not ideal. If I ever changed the css in the style sheet I'd also have to change the CSS in this part on every single page that has this style of table

我已经通过简单地使用$()。css();将重复的css应用于表格,以粗略和准备的方式完成了这项工作。功能,但这并不理想。如果我在样式表中更改了css,我还必须在每个具有此样式表的页面上更改此部分中的CSS

Something like $('.mytable').makeCSSInline(); would be an ideal function - if it existed :)

像$('。mytable')。makeCSSInline();将是一个理想的功能 - 如果它存在:)

edit: Just for clarification: I don't think the copy/paste will retain the css if it's in an internal style sheet (copied using the .load function).. It has to be fully inline (in the style attribute of each tag that has a style associated with it).

编辑:只是为了澄清:我不认为复制/粘贴将保留css如果它在内部样式表(使用.load函数复制)..它必须完全内联(在每个标记的样式属性中)具有与之相关的风格)。

Also, I'm copying from firefox to outlook (so from non-microsoft to microsoft)

另外,我正在从firefox复制到outlook(所以从非微软到微软)

6 个解决方案

#1


17  

This isn't exactly perfect but I think it's pretty close to what you're looking for.

这并不完美,但我认为它非常接近你所寻找的东西。

(function($) {
    $.extend($.fn, {
        makeCssInline: function() {
            this.each(function(idx, el) {
                var style = el.style;
                var properties = [];
                for(var property in style) { 
                    if($(this).css(property)) {
                        properties.push(property + ':' + $(this).css(property));
                    }
                }
                this.style.cssText = properties.join(';');
                $(this).children().makeCssInline();
            });
        }
    });
}(jQuery));

Then you'd just call it with:

然后你只需要调用它:

$('.selector').makeCssInline();

#2


4  

I had the same problem, I wanted to get all css inline for email compatibility, I found a great jQuery plugin

我有同样的问题,我想获得所有css inline的电子邮件兼容性,我发现了一个很棒的jQuery插件

https://github.com/Karl33to/jquery.inlineStyler

https://github.com/Karl33to/jquery.inlineStyler

I know it's a bit late for this question, but it's a very easy solution.

我知道这个问题有点晚了,但这是一个非常简单的解决方案。

$('.mytable').inlineStyler();

Hope it might help

希望它可能有所帮助

#3


3  

I would do a jquery load() and dump it into a style tag

我会做一个jquery load()并将其转储到样式标记中

$("style").load("css/site.css", function() {
    alert('Load was performed.');
});

or if you don't want to have to have an empty style tag to populate you can do this:

或者如果您不想要填充空样式标记,则可以执行以下操作:

$("head").append("<style></style>");
$("head style:last").load("<%=ResolveUrl("~/") %>_res/c/site.css", function() {
   alert('Load was performed.');
});

#4


2  

Mailchimp has an online tool for this:

Mailchimp有一个在线工具:

http://templates.mailchimp.com/resources/inline-css/

http://templates.mailchimp.com/resources/inline-css/

Just paste in your HTML with CSS in the head and it will spit it out with inline styles.

只需在头部粘贴CSS,然后使用内联样式将其吐出。

#5


0  

Use plain JavaScript for this :

使用纯JavaScript进行此操作:

$('.mytable').style.cssText;

Your welcome ;]

不客气 ;]

ps. same for adding inline css:

PS。添加内联css相同:

$('.mytable').style.cssText = "border:1px solid red;";

#6


0  

All solutions, that I've found, was not good enough for me. Here's my own one. When using this, please keep in mind the following:

我发现的所有解决方案对我来说都不够好。这是我自己的。使用时请注意以下事项:

  1. this presumes, that we have all our css styles in an external file, that has an id "#main-css-file".
  2. 这假设我们在外部文件中拥有所有css样式,其id为“#main-css-file”。
  3. declaration !important has no effect: such rules are processed in the same way with ordinary ones.
  4. 声明!重要没有效果:这些规则与普通规则的处理方式相同。
  5. the algorithm is the following: a) save existing inline styles, if they exist; b) apply external css rules; c) restore saved inline styles.
  6. 算法如下:a)保存现有的内联样式(如果存在); b)应用外部css规则; c)恢复保存的内联样式。

Here we go:

开始了:

var content = $('#selector');

// preserve existing inline styles
content.find('[style]').each( function() {
    var that = $(this);
    that.attr( 'data-inline-css', that.attr('style') );
});

// get external css rules and iterate over all of them
var extCssFile  = $('#main-css-file')[0].sheet,
    extCssRules = extCssFile.cssRules;
for ( var i = 0; i < extCssRules.length; i++ ) {
    var extCssRule     = extCssRules[i].cssText,
        extCssSelector = $.trim( extCssRule.substring( 0, extCssRule.indexOf('{') ) ),
        extCssProps    = $.trim( extCssRule.substring( extCssRule.indexOf('{') + 1, extCssRule.indexOf('}') ) );

    // we omit all rules, containing useless/unsupported pseudo classes
    // and also make sure,that we have at least 1 element, matching current selector
    if ( extCssSelector.indexOf(':after') == -1 &&
        extCssSelector.indexOf(':before') == -1 &&
        content.find( extCssSelector ).length
    ) {

        // create array of css properties
        extCssProps = extCssProps.split(';');
        // remove the last array item, if it's empty
        if ( $.trim( extCssProps[ extCssProps.length - 1 ] ) == '' ) {
            extCssProps.pop();
        }

        // iterate over each tag withing content
        content.find( extCssSelector ).each( function() {
            var that = $(this);
            // add css from file
            for ( var a = 0; a < extCssProps.length; a++ ) {
                // split rule on ":", but not on "://", that is a part of url protocol
                var style = extCssProps[a].split(/:(?!\/\/)/),
                    prop  = $.trim( style[0] ),
                    val   = $.trim( style[1] );
                // jQuery doesn't understand css "!important" - remove it
                if ( val.indexOf('important') != -1 ) {
                    val = $.trim( val.replace( '!', '' ).replace( 'important', '' ) );
                }
                that.css( prop, val );
            }
        });
    }
}

// restore inline css, that already existed before applying external css
content.find('[data-inline-css]').each( function() {
    var that = $(this),
        inlCssProps = that.attr('data-inline-css').split(';');
    if ( $.trim( inlCssProps[ inlCssProps.length - 1 ] ) == '' ) {
        inlCssProps.pop();
    }
    for ( var i = 0; i < inlCssProps.length; i++ ) {
        var style = inlCssProps[i].split(/:(?!\/\/)/),
            prop  = $.trim( style[0] ),
            val   = $.trim( style[1] );
        that.css( prop, val );
    }
    that.removeAttr('data-inline-css');
});

#1


17  

This isn't exactly perfect but I think it's pretty close to what you're looking for.

这并不完美,但我认为它非常接近你所寻找的东西。

(function($) {
    $.extend($.fn, {
        makeCssInline: function() {
            this.each(function(idx, el) {
                var style = el.style;
                var properties = [];
                for(var property in style) { 
                    if($(this).css(property)) {
                        properties.push(property + ':' + $(this).css(property));
                    }
                }
                this.style.cssText = properties.join(';');
                $(this).children().makeCssInline();
            });
        }
    });
}(jQuery));

Then you'd just call it with:

然后你只需要调用它:

$('.selector').makeCssInline();

#2


4  

I had the same problem, I wanted to get all css inline for email compatibility, I found a great jQuery plugin

我有同样的问题,我想获得所有css inline的电子邮件兼容性,我发现了一个很棒的jQuery插件

https://github.com/Karl33to/jquery.inlineStyler

https://github.com/Karl33to/jquery.inlineStyler

I know it's a bit late for this question, but it's a very easy solution.

我知道这个问题有点晚了,但这是一个非常简单的解决方案。

$('.mytable').inlineStyler();

Hope it might help

希望它可能有所帮助

#3


3  

I would do a jquery load() and dump it into a style tag

我会做一个jquery load()并将其转储到样式标记中

$("style").load("css/site.css", function() {
    alert('Load was performed.');
});

or if you don't want to have to have an empty style tag to populate you can do this:

或者如果您不想要填充空样式标记,则可以执行以下操作:

$("head").append("<style></style>");
$("head style:last").load("<%=ResolveUrl("~/") %>_res/c/site.css", function() {
   alert('Load was performed.');
});

#4


2  

Mailchimp has an online tool for this:

Mailchimp有一个在线工具:

http://templates.mailchimp.com/resources/inline-css/

http://templates.mailchimp.com/resources/inline-css/

Just paste in your HTML with CSS in the head and it will spit it out with inline styles.

只需在头部粘贴CSS,然后使用内联样式将其吐出。

#5


0  

Use plain JavaScript for this :

使用纯JavaScript进行此操作:

$('.mytable').style.cssText;

Your welcome ;]

不客气 ;]

ps. same for adding inline css:

PS。添加内联css相同:

$('.mytable').style.cssText = "border:1px solid red;";

#6


0  

All solutions, that I've found, was not good enough for me. Here's my own one. When using this, please keep in mind the following:

我发现的所有解决方案对我来说都不够好。这是我自己的。使用时请注意以下事项:

  1. this presumes, that we have all our css styles in an external file, that has an id "#main-css-file".
  2. 这假设我们在外部文件中拥有所有css样式,其id为“#main-css-file”。
  3. declaration !important has no effect: such rules are processed in the same way with ordinary ones.
  4. 声明!重要没有效果:这些规则与普通规则的处理方式相同。
  5. the algorithm is the following: a) save existing inline styles, if they exist; b) apply external css rules; c) restore saved inline styles.
  6. 算法如下:a)保存现有的内联样式(如果存在); b)应用外部css规则; c)恢复保存的内联样式。

Here we go:

开始了:

var content = $('#selector');

// preserve existing inline styles
content.find('[style]').each( function() {
    var that = $(this);
    that.attr( 'data-inline-css', that.attr('style') );
});

// get external css rules and iterate over all of them
var extCssFile  = $('#main-css-file')[0].sheet,
    extCssRules = extCssFile.cssRules;
for ( var i = 0; i < extCssRules.length; i++ ) {
    var extCssRule     = extCssRules[i].cssText,
        extCssSelector = $.trim( extCssRule.substring( 0, extCssRule.indexOf('{') ) ),
        extCssProps    = $.trim( extCssRule.substring( extCssRule.indexOf('{') + 1, extCssRule.indexOf('}') ) );

    // we omit all rules, containing useless/unsupported pseudo classes
    // and also make sure,that we have at least 1 element, matching current selector
    if ( extCssSelector.indexOf(':after') == -1 &&
        extCssSelector.indexOf(':before') == -1 &&
        content.find( extCssSelector ).length
    ) {

        // create array of css properties
        extCssProps = extCssProps.split(';');
        // remove the last array item, if it's empty
        if ( $.trim( extCssProps[ extCssProps.length - 1 ] ) == '' ) {
            extCssProps.pop();
        }

        // iterate over each tag withing content
        content.find( extCssSelector ).each( function() {
            var that = $(this);
            // add css from file
            for ( var a = 0; a < extCssProps.length; a++ ) {
                // split rule on ":", but not on "://", that is a part of url protocol
                var style = extCssProps[a].split(/:(?!\/\/)/),
                    prop  = $.trim( style[0] ),
                    val   = $.trim( style[1] );
                // jQuery doesn't understand css "!important" - remove it
                if ( val.indexOf('important') != -1 ) {
                    val = $.trim( val.replace( '!', '' ).replace( 'important', '' ) );
                }
                that.css( prop, val );
            }
        });
    }
}

// restore inline css, that already existed before applying external css
content.find('[data-inline-css]').each( function() {
    var that = $(this),
        inlCssProps = that.attr('data-inline-css').split(';');
    if ( $.trim( inlCssProps[ inlCssProps.length - 1 ] ) == '' ) {
        inlCssProps.pop();
    }
    for ( var i = 0; i < inlCssProps.length; i++ ) {
        var style = inlCssProps[i].split(/:(?!\/\/)/),
            prop  = $.trim( style[0] ),
            val   = $.trim( style[1] );
        that.css( prop, val );
    }
    that.removeAttr('data-inline-css');
});