【问题标题】:jQuery convert applied classes to style attributesjQuery 将应用的类转换为样式属性
【发布时间】:2013-08-01 11:45:07
【问题描述】:

我正在做一个书签项目。因此,当用户点击书签时,他可以抓取网页的一部分并在其他地方查看。

问题在于部分元素(假设为 div)应用了 css 样式和类。

有什么方法可以循环遍历选定 div 的所有子元素并将类属性转换为样式属性以便我可以保持格式设置?

例如下面的示例截图; 我需要取出所有应用的类,并将它们转换为选定区域的样式属性。

【问题讨论】:

  • 所以你想从类中提取样式并将它们应用为内联样式?
  • 如果您打开“Computed Style”面板,您可以看到所选元素的所有样式。您可以使用 JavaScript 遍历每个元素上的每个计算样式(无论是由类还是由浏览器设置)并保存所有样式。这是 JavaScript 中的 how to get computed styles
  • @CodyGuldner 是的,没错。
  • @RoryO'Kane 感谢您的链接。
  • 这就是你要找的jsfiddle.net/pkuVk

标签: jquery css


【解决方案1】:

固定在引导程序中使用

(function($) {
    $.extend($.fn, {
        makeCssInline: : function(sizes) {
            this.each(function(idx, el) {
                var style = el.style;
                var properties = [];
                for(var property in style) {
                    if(property=="height" || property=="width") { continue; }
                    if($(this).css(property)) {
                        properties.push(property + ':' + $(this).css(property));
                    }
                }

                if(sizes) {
                    properties.push("width" + ':' + $(this).width()+"px");
                    properties.push("height" + ':' + $(this).height()+"px");
                }

                this.style.cssText = properties.join(';');
                $(this).children().makeCssInline();
            });
        }
    });
}(jQuery));

【讨论】:

    【解决方案2】:
    (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));
    

    你可以用

    来调用它
    $(".select").makeCSSInline();
    

    这个函数的问题在于它会将每个 CSS 属性都带入标签,因此它可能会导致严重的性能损失,但如果你愿意冒这个风险,请继续

    Fiddle

    here获取的函数

    【讨论】:

    • 很好的解决方案,很讨厌,但可以完成工作。正如您的声明所暗示的,这应该是最后的手段,并附带“外科医生警告”:Your users may experience lag, performance, or health concerns with repeated use of this solution
    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2011-08-01
    • 2016-08-25
    相关资源
    最近更新 更多