Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery获取多个CSS属性_Javascript_Jquery - Fatal编程技术网

Javascript 使用jQuery获取多个CSS属性

Javascript 使用jQuery获取多个CSS属性,javascript,jquery,Javascript,Jquery,我知道您可以像这样设置多个css属性: $('#element').css({property: value, property: value}); 但是如何使用CSS获得多个属性呢? 有什么解决办法吗?最简单的方法?删除jQuery var e = document.getElementById('element'); var css = e.currentStyle || getComputedStyle(e); // now access things like css.color, c

我知道您可以像这样设置多个css属性:

$('#element').css({property: value, property: value});
但是如何使用CSS获得多个属性呢?
有什么解决办法吗?

最简单的方法?删除jQuery

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

您可以创建自己的jQuery函数来执行此操作: ​

jquery的css方法(从1.9开始)说,您可以传递一个属性字符串数组,它将返回一个具有键/值对的对象

例如:


你是说你想要一个带有给定CSS属性集的地图?你说得到多个CSS属性是什么意思?是的,我也会这么做。我只是想知道为什么这还没有内置。这是合乎逻辑的,因为您可以设置单个属性或设置多个属性。我自动假设您可以获得单个属性,甚至可以获得多个属性(将数组传递给.css()),但他们似乎忘记了。此外,FWIW此方法比多次调用
.css()
要快。。。谁会想到呢?;)@peipst9lker,当然,纯JS比jQuery快!尽管如此,您还是必须绕过浏览器支持(currentStyle vs getComputedStyle)。权衡……如我的回答所示,在这种情况下,解决浏览器支持问题非常简单。它与手动事件处理中常用的
e=e | | event.event
窗口一样简单。
//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;
};
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element
$( elem ).css([ 'property1', 'property2', 'property3' ]);