简体   繁体   English

使用jQuery获取多个CSS属性

[英]Get multiple CSS properties with jQuery

I know you can SET multiple css properties like so: 我知道您可以像这样设置多个CSS属性:

$('#element').css({property: value, property: value});

But how do I GET multiple properties with CSS? 但是,如何使用CSS获取多个属性? Is there any solution at all? 有什么解决办法吗?

jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs. jQuery的css方法(从1.9开始)说,您可以传递属性字符串数组,它将返回带有键/值对的对象。

eg: 例如:

$( elem ).css([ 'property1', 'property2', 'property3' ]);

http://api.jquery.com/css/ http://api.jquery.com/css/

Easiest way? 最简单的方法? Drop the jQuery. 删除jQuery。

var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.

You can create your own jQuery function to do this: ​ 您可以创建自己的jQuery函数来执行此操作:

//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {

    //create an output variable and limit this function to finding info for only the first element passed into the function
    var output = {},
        self   = this.eq(0);

    //iterate through the properties passed into the function and add them to the output variable
    for (var i = 0, len = propertyArray.length; i < len; i++) {
        output[propertyArray[i]] = this.css(propertyArray[i]);
    }
    return output;
};

Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output) 这是一个演示: http : //jsfiddle.net/6qfQx/1/ (检查控制台日志以查看输出)

This function requires an array to be passed in containing the CSS properties to look-up. 此函数需要传递一个包含要查找的CSS属性的数组。 Usage for this would be something like: 用法如下所示:

var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element

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

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