博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jQuery是否可以获取与元素关联的所有CSS样式?
阅读量:2291 次
发布时间:2019-05-09

本文共 4826 字,大约阅读时间需要 16 分钟。

本文翻译自:

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all? jQuery中是否有一种方法可以从现有元素中获取所有CSS并将其应用于另一个元素而不列出所有元素?

I know it would work if they were a style attribute with attr() , but all of my styles are in an external style sheet. 我知道如果它们是attr()的样式属性,它将起作用,但是我所有的样式都在外部样式表中。


#1楼

参考:


#2楼

@marknadal's solution wasn't grabbing hyphenated properties for me (eg max-width ), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations: @marknadal的解决方案不是为我获取带连字符的属性(例如max-width ),但是更改css2json()的第一个for循环使其有效,并且我怀疑执行的迭代次数更少:

for (var i = 0; i < css.length; i += 1) {    s[css[i]] = css.getPropertyValue(css[i]);}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase(). 通过length而不是in,循环in,通过getPropertyValue()而不是toLowerCase().检索toLowerCase().


#3楼

I had tried many different solutions. 我尝试了许多不同的解决方案。 This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. 这是唯一对我有用的方法,因为它能够选择在类级别应用的样式以及在元素上直接赋予的样式。 So a font set at css file level and one as a style attribute; 因此,在css文件级别设置一种字体,并将其作为样式属性。 it returned the correct font. 它返回了正确的字体。

It is simple! 很简单! (Sorry, can't find where I originally found it) (对不起,找不到我最初找到它的地方)

//-- html objectvar element = htmlObject; //e.g document.getElementById//-- or jquery objectvar element = htmlObject[0]; //e.g $(selector)var stylearray = document.defaultView.getComputedStyle(element, null);var font = stylearray["font-family"]

Alternatively you can list all the style by cycling through the array 或者,您可以通过循环遍历数组来列出所有样式

for (var key in stylearray) {console.log(key + ': ' + stylearray[key];}

#4楼

A couple years late, but here is a solution that retrieves both inline styling and external styling: 迟了几年,但是这里有一个可以同时检索内联样式和外部样式的解决方案:

function css(a) {    var sheets = document.styleSheets, o = {};    for (var i in sheets) {        var rules = sheets[i].rules || sheets[i].cssRules;        for (var r in rules) {            if (a.is(rules[r].selectorText)) {                o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));            }        }    }    return o;}function css2json(css) {    var s = {};    if (!css) return s;    if (css instanceof CSSStyleDeclaration) {        for (var i in css) {            if ((css[i]).toLowerCase) {                s[(css[i]).toLowerCase()] = (css[css[i]]);            }        }    } else if (typeof css == "string") {        css = css.split("; ");        for (var i in css) {            var l = css[i].split(": ");            s[l[0].toLowerCase()] = (l[1]);        }    }    return s;}

Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css() , ex: 将jQuery对象传递到css() ,它将返回一个对象,然后您可以将其插入jQuery的$().css() ,例如:

var style = css($("#elementToGetAllCSS"));$("#elementToPutStyleInto").css(style);

:) :)


#5楼

Two years late, but I have the solution you're looking for. 迟了两年,但是我有您想要的解决方案。 Not intending to take credit form the , here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE. 我不打算从那里获得任何荣誉,这是我发现的一个插件,可以很好地满足您的需求,但是可以在所有浏览器(甚至IE)中获得所有可能的样式。

Warning: This code generates a lot of output, and should be used sparingly. 警告:此代码会产生大量输出,应谨慎使用。 It not only copies all standard CSS properties, but also all vendor CSS properties for that browser. 它不仅复制所有标准CSS属性,而且还复制该浏览器的所有供应商CSS属性。

jquery.getStyleObject.js:

/* * getStyleObject Plugin for jQuery JavaScript Library * From: http://upshots.org/?p=112 */(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, l = style.length; i < l; i++){                var prop = style[i];                var camel = prop.replace(/\-([a-z])/g, camelize);                var val = style.getPropertyValue(prop);                returns[camel] = val;            };            return returns;        };        if(style = dom.currentStyle){            for(var prop in style){                returns[prop] = style[prop];            };            return returns;        };        return this.css();    }})(jQuery);

Basic usage is pretty simple, but he's written a function for that as well: 基本用法非常简单,但是他也为此编写了一个函数:

$.fn.copyCSS = function(source){  var styles = $(source).getStyleObject();  this.css(styles);}

Hope that helps. 希望能有所帮助。


#6楼

Why not use ? 为什么不使用 ? It's an object which contains members such as width and backgroundColor . 这是一个包含成员的对象,例如widthbackgroundColor

转载地址:http://kwjnb.baihongyu.com/

你可能感兴趣的文章
DeepLearning 知识点整理
查看>>
stdcall 标准winNTdll 编写 与 调用
查看>>
Android 搭建
查看>>
Java 配置
查看>>
多个Activity的完全退出
查看>>
自定义android控件
查看>>
tomcat c/s 三层架构
查看>>
代码_多进程_简单实例
查看>>
转载_消息机制
查看>>
代码_网络_FTP
查看>>
代码_网络_WWW
查看>>
UIView常用属性和函数
查看>>
UIButton常用属性和函数详解
查看>>
UILabel常用属性详解
查看>>
UITextField常用属性和方法详解
查看>>
“UITableView完美平滑滚动”阅读笔记
查看>>
UIImageView常用属性和方法
查看>>
UIImage常用属性和方法
查看>>
会报编译器警告的Xcode 6.3新特性:Nullability Annotations
查看>>
2015 Objective-C 三大新特性
查看>>