简体   繁体   English

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

[英]Copying CSS to inline using jquery (or retaining formatting when copying stuff from a web page)

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. 给定一个应用了css类的表,类定义在外部样式表中(样式应用于th,tr和td)我想移动或将该css复制到标记本身的style属性。 In other words I want to make the CSS inline. 换句话说,我想让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. 如果他们在具有外部源CSS的表上执行此操作,则粘贴的表将丢失所有格式。 If the css is inline the formatting is retained. 如果css是内联的,则保留格式。

I have already done this in a rough-and-ready way by simply applying duplicated css to the table using $().css(); 我已经通过简单地使用$().css();将重复的css应用于表来以粗略和准备的方式完成此操作$().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

Something like $('.mytable').makeCSSInline(); 类似于$('.mytable').makeCSSInline(); would be an ideal function - if it existed :) 将是一个理想的功能 - 如果它存在:)

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(所以从非微软到微软)

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();

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 希望它可能有所帮助

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: 或者如果您不想要填充空style标记,则可以执行以下操作:

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

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在头部粘贴HTML,它就会使用内联样式将其吐出。

Use plain JavaScript for this : 使用纯JavaScript进行此操作:

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

Your welcome ;] 别客气 ;]

ps. PS。 same for adding inline css: 添加内联css相同:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM